/*************************************************
File name:	paraCommMain.c
Author: 	Cui Ticun
Version:	9:00:00 
Date:  		2007-7-2
Description:
						
History:               
No. 
Author  
Date    
Version   
Description
*************************************************/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

#include "paraComm.h"

static struct itimerval itimer, old_itimer;

void onParaCommTimer();
void setParaCommTimer();
void setup_daemon(void);
int timerCounter = 0;

int main(int argc, char *argv[])
{
	char runMode;

	runMode = getopt(argc, argv, "d");
	switch (runMode) {
	case 'd':
		setup_daemon();
		break;
	case '?':
		break;
	}
	debug_init();
	fprintf(stderr, "\n Calling iptrans_init() \n");
	iptrans_init();

	fprintf(stderr, "\n Calling snmp_init() \n");
	snmp_init(4957);

	fprintf(stderr, "\n Calling paraCommInit() \n");
	if(paraCommInit()<=0)
	{
		exitLog("paraComm:main, paraCommInit function error");
		exit(1);
	}

	setParaCommTimer();

	while (1) {
		usleep(50);
	}

	return (1);
}

void onParaCommTimer()
{
	paraCommTimer();
	/*
	if (timerCounter > 5) {
		paraCommTimer();
		timerCounter = 0;
	}
	timerCounter++;
	*/
}

void setParaCommTimer()
{
	struct sigaction act;
	act.sa_handler = onParaCommTimer;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	if (sigaction(SIGALRM, &act, NULL) < 0) {
		perror("Produce Sigaction");
		exitLog("paraComm:setParaCommTimer, 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("paraComm:setParaCommTimer, 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;
		}
	}
}
