/*
 * Copyright (c) 2005, 2006 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: greyrm.c,v 1.5 2006/11/30 04:32:59 ca Exp $")

#include "sm/assert.h"
#include "sm/error.h"
#include "sm/memops.h"
#include "sm/net.h"
#include "sm/time.h"
#include "sm/sysexits.h"
#include "sm/greyctl.h"
#include "sm/bdb.h"
#if MTA_USE_PTHREADS
#include "sm/pthread.h"
#endif
#include "greyctl.h"

static int Verbose = 0;
#define MAX_BUF_LEN_TIME	32

static sm_ret_T
sm_grey_opendb(const char *db_name, DB **pdb, const char *sdb_name, DB **psdb)
{
	int ret;
	DB *db, *sdb;
#define dbenv	NULL

	SM_REQUIRE(db_name != NULL);
	SM_REQUIRE(pdb != NULL);
	SM_REQUIRE(sdb_name != NULL);
	SM_REQUIRE(psdb != NULL);

	/* create/open primary */
	ret = db_create(&db, dbenv, 0);
	if (ret != 0)
		return ret;
	ret = db->open(db, NULL, db_name, NULL, DB_BTREE, 0, 0600);
	if (ret != 0)
		return ret;

	/* create/open secondary */
	ret = db_create(&sdb, dbenv, 0);
	if (ret != 0)
		return ret;
	ret = sdb->set_bt_compare(sdb, sm_grey_compare);
	if (ret != 0)
		return ret;
	ret = sdb->set_flags(sdb, DB_DUP | DB_DUPSORT);
	if (ret != 0)
		return ret;
	ret = sdb->open(sdb, NULL, sdb_name, NULL, DB_BTREE, 0, 0600);
	if (ret != 0)
		return ret;

	/* Associate the secondary with the primary. */
	ret = db->associate(db, NULL, sdb, sm_grey_si, 0);
	if (ret != 0)
		return ret;

	*pdb = db;
	*psdb = sdb;
	return SM_SUCCESS;
}

int
main(int argc, char *argv[])
{
	int c;
	sm_ret_T ret;
	char *db_name, *sdb_name, *ipv4, *end;
	ipv4_T addr;
	DB *db, *sdb;
#define DB_NAME "grey_grey_m.db"
#define DBS_NAME "grey_grey_s.db"

	db_name = DB_NAME;
	sdb_name = DBS_NAME;
	while ((c = getopt(argc, argv, "V")) != -1)
	{
		switch (c)
		{
		  case 'V':
			++Verbose;
			break;
		  default:
			return EX_USAGE;
		}
	}
	argc -= optind;
	argv += optind;
	db = NULL;
	sdb = NULL;

	ret = sm_grey_opendb(db_name, &db, sdb_name, &sdb);
	if (sm_is_err(ret))
		return ret;

	for (c = 0; c < argc; c++)
	{
		ipv4 = argv[c];
		ret = sm_inet_a2ipv4(ipv4, &end, &addr);
		if (sm_is_err(ret))
		{
			sm_io_fprintf(smioerr,
				"error: %s is not an IPv4 address\n",
				ipv4);
			continue;
		}
		ret = sm_grey_rm(db, (uchar *)&addr, sizeof(addr));
		if (sm_is_err(ret))
		{
			sm_io_fprintf(smioerr,
				"error: %s not removed, status=%m\n",
				ipv4);
			continue;
		}
		else if (Verbose > 0)
			sm_io_fprintf(smioerr, "%s removed\n", ipv4);
	}
	if (sdb != NULL)
	{
		sdb->close(sdb, 0);
		sdb = NULL;
	}
	if (db != NULL)
	{
		db->close(db, 0);
		db = NULL;
	}
	return 0;
}


syntax highlighted by Code2HTML, v. 0.9.1