/* 
 *  Ths code in this file is part of tcptrack. For more information see
 *    http://www.rhythm.cx/~steve/devel/tcptrack
 *
 *     Copyright (C) Steve Benson - 2003
 *
 *  tcptrack 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, or (at your
 *  option) any later version.
 *   
 *  tcptrack is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  General Public License for more details.
 *   
 *  You should have received a copy of the GNU General Public License
 *  along with GNU Make; see the file COPYING.  If not, write to
 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 
 *  
 */
#define _BSD_SOURCE 1
#define _REENTRANT
#include "../config.h" // for PACKAGE and VERSION
#include <stdio.h>
#include <unistd.h> // for getopt & pause
#include <limits.h> // for ARG_MAX
#include "TCContainer.h"
#include "TextUI.h"
#include "util.h"
#include "PacketBuffer.h"
#include "Sniffer.h"
#include "Logger.h"

Logger *logger;

void printusage(int argc,char **argv)
{
	printf("Usage: %s [-hv] -i <interface> [<filter expression>]\n",argv[0]);
}

struct config parseopts(int argc, char **argv)
{
	int o;
	struct config cf;
	cf.fexp = (char *) malloc( sizeof(char) * ARG_MAX ); // TODO: leaked
	cf.fexp[0]='\0';
	bool got_iface=false;
	
	while( (o=getopt(argc,argv,"hvi:")) > 0 )
	{
		switch(o)
		{
			case 'h':
				printusage(argc,argv);
				exit(0);
			case 'v':
				printf("%s v%s\n",PACKAGE,VERSION);
				exit(0);
			case 'i':
				cf.iface = optarg;
				got_iface=true;
		}
	}
	
	if( ! got_iface ) {
		printusage(argc,argv);
		exit(1);
	}
	
	for( int i=optind; i<argc; i++ )
		sprintf(cf.fexp,"%s %s",cf.fexp,argv[i]);
	
	return cf;
}

int main(int argc, char **argv)
{
	if( geteuid() != 0 ) {
		printf("%s must be run as root.\n",argv[0]);
		exit(1);
	}
	
	struct config cf = parseopts(argc,argv);

	logger = new Logger(false);
	logger->log("starting");

	TCContainer *c = new TCContainer();
	PacketBuffer *pb = new PacketBuffer(c);
	Sniffer *s = new Sniffer(pb,cf.iface,cf.fexp);
	TextUI *ui = new TextUI(c);

	s->start();

	pause(); 
}


