/* Title:	beatSendMain.c
 * Description:	beatSend main program
 * Author:	Cui Ticun
 * Date:	2006-6-29
 */

#include "beatSend.h"

static struct itimerval itimer, old_itimer;
unsigned long timerCount;

//get from omcd.conf
int omcTypeNo = 0;
int omcSysNo = 0;
int omcSubSysNo = 0;
omcBaseInfo omcInfo = { 0, 0, 0, 0, {1, 2, 3} };

BYTE sequenceNum[4]={0,0,0,0};

void onTimerProc();
void setTimer(void);
void setup_daemon(void);

/* by simon at 23/10/07 */
int corefile_flag = 0;

int main(int argc, char *argv[])
{
	char runMode;
	runMode = getopt(argc, argv, "d");

	debug_init(1);				//must do it at first
	
	snmp_init(4957);
	
	heartbeat_init(0);

	beatSendInit(&omcInfo,sequenceNum);

	setTimer();
	switch (runMode) {
	case 'd':
		setup_daemon();
		break;
	case '?':
		break;
	}

	while (1) {
		usleep(50);
	}

	return (1);
}


void onTimerProc()
{
	if (timerCount >= 50) {
		beatSend(1,0);
	}

	if (timerCount > 1000 * 3600) {
		timerCount = 0;
	}
	
	timerCount++;
}

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