/*
 * Copyright (c) 2004, 2005 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: t-ringinsert.c,v 1.4 2005/04/14 17:08:56 ca Exp $")
#include "sm/types.h"
#include "sm/str.h"
#include "sm/ring.h"
#include "sm/mta.h"
#include "sm/test.h"
#include "sm/io.h"
#include "sm/sysexits.h"

#include "t-ringins.h"
#include "t-ringinschk.h"
#include "t-ringinsert.h"

static sm_ret_T
aqr_test0(uint lim, uint flags)
{
	sm_ret_T ret;
	uint i;
	int r;
	sm_str_P str;
	char buf[RCPT_MAX_LEN];
	aq_rcpt_P aq_rcpt, aq_rcpt_prev;

	aq_rcpt_prev = NULL;
	aq_rcpt = NULL;
	ret = SM_SUCCESS;
	srand(time(0));
	for (i = 0; i < lim; i++)
	{
		aq_rcpt = sm_zalloc(sizeof(*aq_rcpt));
		SM_TEST_ERR(aq_rcpt != NULL);

		r = rand();
		if (Verbose > 1)
			sm_io_fprintf(smioout, "i=%u, r=%8d\n", i, r);
		sm_snprintf(buf, sizeof(buf), "%d-domain.tld-%u", r, i);

		str = sm_str_scpy0(NULL, buf, sizeof(buf));
		aq_rcpt->aqr_domain = str;
		str = NULL;
		if (SM_IS_FLAG(flags, SMT_APPEND))
		{
			if (aq_rcpt_prev == NULL)
				AQR_SS_INIT(aq_rcpt);
			else
				AQR_SS_APP(aq_rcpt_prev, aq_rcpt);
		}
		else
		{
			if (aq_rcpt_prev == NULL)
				AQR_SS_INIT(aq_rcpt);
			else
				ret = ring_insert(AQR_SS2R(aq_rcpt_prev),
					AQR_SS2R(aq_rcpt));
			if (sm_is_err(ret))
				goto error;
		}
		aq_rcpt_prev = aq_rcpt;
		if (!SM_IS_FLAG(flags, SMT_NOCHECKS))
			ret = aqr_test1(aq_rcpt, i);
	}

	if (!SM_IS_FLAG(flags, SMT_NOCHECKS))
		ret = aqr_test1(aq_rcpt, i - 1);
	return ret;

  error:
	return ret;
}

static void
usage(const char *prg)
{
	sm_io_fprintf(smioerr, "usage: %s [options]\n", prg);
	sm_io_fprintf(smioerr, "Test AQ recipient sorting (domains are random numbers)\n");
	sm_io_fprintf(smioerr, "options:\n");
	sm_io_fprintf(smioerr, "-a    append only, don't sort\n");
	sm_io_fprintf(smioerr, "-n n  specify number of recipients to sort\n");
	sm_io_fprintf(smioerr, "-t    don't perform tests, just sort\n");
	sm_io_fprintf(smioerr, "-V    increase verbosity\n");
	exit(0);
}


int
main(int argc, char **argv)
{
	int c;
	uint n, flags;
	sm_ret_T r;
	char *prg;

	prg = argv[0];
	n = SM_AQ_RCPTS;
	flags = 0;
	while ((c = getopt(argc, argv, "an:tV")) != -1)
	{
		switch (c)
		{
		  case 'a':
			flags |= SMT_NOCHECKS|SMT_APPEND;
			break;
		  case 'n':
			n = (uint) strtoul(optarg, NULL, 0);
			break;
		  case 't':
			flags |= SMT_NOCHECKS;
			break;
		  case 'V':
			++Verbose;
			break;
		  default:
			usage(prg);
			return(EX_USAGE);
		}
	}

	sm_test_begin(argc, argv, "test adbr 0");

	r = aqr_test0(n, flags);

	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1