#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <signal.h>
#include <time.h>
#include "defs.h"
#include "irc.h"
#include "config.h"
#include "plugin.h"

void do_alarm();

extern char PETNICK[32];
extern char PETSERVER[255];
extern char PETPORT[4];
extern time_t LAST_RECV;

int PETSHUTDOWN = 0;
int DEBUG = 0;
int ALARMED = 0;
int CONNECTED = 0;

int main(int argc, char *argv[]) {
	fd_set read;
	int fdmax;
	int fd;
	int retval;
	int pretimeout = 0;
        pid_t pid;
	time_t present;

	FD_ZERO(&read);
	if (argc >= 2) {
		if (strcmp(argv[1],"-debug") == 0)
			DEBUG = 1; //Show Everything!
	}

	if (conf_read() == 1) { //Read Conf
		printf("Configuration failed...\n");
		exit(1);
	}

	if (!DEBUG) {
		pid = fork(); //fork into the background
		if (pid == -1) {
			perror("fork");
			exit(1);
		} else if (pid != 0) { //close parent process
			printf("Slipping into the night....\n");
			exit(0);
		}
	}

	signal(SIGALRM,do_alarm);
	alarm(1); //set up 1 second generic timer

	while (PETSHUTDOWN == 0) { //PETSHUTDOWN gets set if it is disconnected or told to shutdown
		while ((fd = irc_connect()) == -1) {
			sleep(3); //wait a few seconds before reconnecting
		}
		CONNECTED = 1;
		FD_SET(fd,&read);
		fdmax = fd;
		irc_start(fd); //send NICK and USER
		time(&LAST_RECV);
		while (CONNECTED == 1 && PETSHUTDOWN == 0) {

			FD_ZERO(&read);
       			FD_SET(fdmax,&read);
			retval = select(fdmax+1, &read, NULL, NULL, NULL);
			switch(retval) {
				case 0:
					break;
				case -1:
					break;
				default:
					recvfrom_irc(fdmax); //handle irc data
			}
			if(ALARMED) {
				time(&present);
                                if ((present - LAST_RECV) >= (IRCTIMEOUT / 2)) {
                                        if (CONNECTED == 1) {
                                             if(pretimeout == 0) {
                                                  //Ping the server after half of timeout reached every 30 seconds
                                                  putirc("PING :12345678\n");
                                                  pretimeout = 30;
                                             } else {
                                                  pretimeout--;
                                             }
                                        }
                                }
				if ((present - LAST_RECV) >= IRCTIMEOUT) {
					//Bot timed out
					close(fd);
					CONNECTED = 0;
				} else {
					if(qlength > 0)
						irc_sendq(fd);
					plugin_timer(); //check plugins
				}
				ALARMED = 0; //we get here every second, this will be the sendq stuff eventually
			}
		}
		plugin_botdisconnect(); //disconnected!
	}

	if (DEBUG)
		printf("Shutting down!\n");
	close(fd);
        return 0;
}

void do_alarm() {
	ALARMED = 1;
	alarm(1);
}

