/* Title:	logCollectorMain.c
 * Description:	test
 * Author:	
 * Date:	
 */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

#include "logCollector.h"

static struct itimerval itimer, old_itimer;

void onTimer();
void setTimer();
void setup_daemon(void);
int timerCounter = 0;

int main(int argc, char *argv[])
{
	char runMode;
	debug_init();
	fprintf(stderr, "\n Calling iptrans_init()");
	iptrans_init();

	fprintf(stderr, "\n Calling logCollectorInit()");
	logCollectorInit();

	if (argc > 0) {
		runMode = getopt(argc, argv, "d");
		switch (runMode) {
		case 'd':
			setup_daemon();
			break;
		case '?':
			exit(0);
			break;
		}
		//debug_init();//must do it at first
	}
	setTimer();
	while (1) {
		usleep(50);
	}

	return (1);
}

void onTimer()
{
	//debug_rt();
	//snmp_timer();
	if (timerCounter % 3 == 0) {
		logCollectorTimer();
	}
	if (timerCounter >= 50000) {
		//logCollectorInit();
		timerCounter = 0;
	}
	timerCounter++;
}

void setTimer()
{
	struct sigaction act;
	act.sa_handler = onTimer;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	if (sigaction(SIGALRM, &act, NULL) < 0) {
		perror("Produce Sigaction");
		exitLog("logCollector:setTimer, sigaction function error");
		exit(1);
	}

	itimer.it_interval.tv_sec = 0;
	itimer.it_interval.tv_usec = 20 * 1000;
	itimer.it_value.tv_sec = 0;
	itimer.it_value.tv_usec = 20 * 1000;

	if (setitimer(ITIMER_REAL, &itimer, &old_itimer) != 0) {
		printf("Setting Timer  error! \n");
		exitLog("logCollector:setTimer, setitimer function error");
		exit(1);
	}
}

void setup_daemon(void)
{
	/*
	int i;

	for (i = 0; i < 3; ++i) {
		close(i);
	}
	*/
	switch (fork()) {
	case -1:
		perror("setup_daemon(), 1st fork()");
		exit(2);
	default:
		exit(0);
	case 0:
		if (setsid() == -1) {
			perror("setup_daemon(), setsid()");
			exit(3);
		}
		switch (fork()) {
		case -1:
			perror("setup_daemon(), 2nd fork()");
			exit(3);
		default:
			exit(0);
		case 0:
			umask(0);
			/* and return with daemon set up */
			return;
		}
	}
}
