/*
 * s2generator.cpp - Silencer Toolkit Example Application
 *
 * Written by Michael "Mr. Sump" Poppitz.
 */
  
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/



#include <string.h>
#include <stdlib.h>
#include <time.h>

#include "call.h"
#include "packet.h"
#include "factory.h"
#include "trx.h"

void main(int argc, char **argv) {
	if (
		argc < 5
		|| argv[1][0] != '-'
		|| strlen(argv[1]) != 2
		|| !strchr("sdum", argv[1][1])
		|| !strncmp(argv[argc - 1], "-v", 2)
	) {
		printf("%s: -s|-d|-u|-m device count [source] destination [-v digi1 [digi2 [...]]]\n\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	bool source = false;
	int dcount = 0;
	int dstart = 0;
	if (argc == 6) {
		source = true;
	} else if (argc > 6) {
		if (!strncmp(argv[6], "-v", 2)) {
			source = true;
			dstart = 7;
		} else {
			dstart = 6;
		}
		dcount = argc - dstart;
	}

	srandom(time(NULL));

	TRX *trx = new TRX();
	if (trx->init() < 0) {
		perror("init");
		exit(EXIT_FAILURE);
	}

	PacketFactory *pf = new PacketFactory(argv[2]);

	Call *d;
	if (!source) {
		d = new Call(argv[4]);
	} else {
		d = new Call(argv[5]);
	}

	int count = 0;
	sscanf(argv[3], "%i", &count);
	if (count < 1 || count > 100)
		count = 1;

	for (int i = 0; i < count; i++) {
		Call *s;
		if (!source) {
			char rndcall[7];
			rndcall[0] = 'A' + (char )((26.0 * rand()) / RAND_MAX);
			rndcall[1] = 'A' + (char )((26.0 * rand()) / RAND_MAX);
			rndcall[2] = '0' + (char )((10.0 * rand()) / RAND_MAX);
			rndcall[3] = 'A' + (char )((26.0 * rand()) / RAND_MAX);
			rndcall[4] = 'A' + (char )((26.0 * rand()) / RAND_MAX);
			rndcall[5] = 'A' + (char )((26.0 * rand()) / RAND_MAX);
			rndcall[6] = 0;
			s = new Call(rndcall, 0);
		} else {
			s = new Call(argv[4]);
		}

		Packet *pa;
		switch (argv[1][1]) {
			case 's': pa = pf->produceSABM(s, d); break;
			case 'd': pa = pf->produceDISC(s, d); break;
			case 'u': pa = pf->produceUA(s, d); break;
			case 'm': pa = pf->produceDM(s, d); break;
		}
	
		pa->setRepeaterCount(dcount);
		for (int i = 0; i < dcount; i++) {
			Call *r = new Call(argv[dstart + i]);
			pa->setRepeaterCall(i, r);
			delete r;
		}

		trx->tx(pa);

		delete pa;
		delete s;
	}

	delete d;
	delete pf;
	delete trx;

	exit(EXIT_SUCCESS);
}
