#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include "f.h"
#include <mysql.h>
#include "dbsql.h"
#include "db.h"
#include "glb.h"
#include "soc.c"

//GLOBALS	
glb_enviroment enviroment;

int get_line_base, get_line_cnt;
db_init dbs;
//_______

#include "glb_conf.c"

int main(){
int i,el,estatus, w, fdes, j, c, n, noo;
pid_t pid;	
char old_min[8], ev_tid[40];
char foo[40] ,foo2[40];
db_event *ptr, *eventtable;
//FILE *eventd_fp_child;
char pipestring[200];
char eid[40];
int crondsock, nbytes;
int actiondsock;

	i = 3;
	j = sysconf(_SC_OPEN_MAX);
	while (i < j) close(i++);

	load_enviroment();

	if(!(crondsock = createsocket(enviroment.crond,1))) _exit(0);
//	if(!(actiondsock = createsocket(enviroment.actiond,1))) _exit(0);


	strcpy(dbs.db,"emrdb");
	db_connect_db();						// connect deamon to db
	db_open_db( (char *) &dbs.db);
	eventtable = db_load_events(&noo);				// load eventtable
	db_disconnect_db();						// resource preserving 

	fprintf(stderr,"Crond started.\n");
start:									//deamon-loop
	sleep(1);							// lower deamon cpu usage
	pipestring[0] = 0;
	nbytes = recv(crondsock,pipestring,100,0);
	if(nbytes < 0) goto cron;
	if(!strncmp(pipestring,"kill",4)){
		unlink(enviroment.crond);
		close(crondsock);
		fprintf(stderr,"Crond stoped.\n");
		_exit(0);
	}
	if(!strncmp(pipestring,"reload",6)){
		free(eventtable);
		db_connect_db();			// connect deamon to db
		db_open_db( (char *) &dbs.db);
		eventtable = db_load_events(&noo);		// reload eventtable
		db_disconnect_db();				// resource preserving 
	}
cron:
	klocka((void *) &ev_tid);			// get current time
	if (!strncmp(ev_tid,old_min,2)) goto start;	// only check events once in a minute
	strncpy(old_min,ev_tid,2);			// set old minute as current
	ptr = eventtable;
	el = noo;			// how many events to loop through	
	while(el){
		if(!strncmp(ptr->edate, ev_tid, 2)){	// check if right minute
			w = 5;	 // check four instans.. we've already checked minute above
			while(--w){
				if (!strncmp(wordcpy(foo,ptr->edate,w),"*",1)) continue;
				if (!strcmp(wordcpy(foo,ptr->edate,w),wordcpy(foo2,ev_tid,w))) continue;
				break;
			}
			if (!w){
			sprintf(eid,"event %d",ptr->eid);
			//sendsocket(crondsock,enviroment.actiond,eid);
			}
		}
		el--;
		ptr++;
	}	// loop checking event table
	goto start;
}
