#include <stdio.h>
#include <rpc/rpc.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/signal.h>
#include <sys/msg.h>
#include <sys/ipc.h>

#include "msgq.h"
#include "defn.h"
#include "Coordinator.h"

//#define     TIMEOUT     100 //Commented by Ameeeeet
//#define     TIMEOUT     10
#define TIMEOUT DEFAULT_MONITOR_NODE_POLL_TIME
char        ipAddr[50];
int         NodeId;
int         pid;
int         msgQueueId;

void handler() {
    TimerMesg   msg;
    int         len;

#ifdef PRINT	    

    printf( "In msg_handler \n");

#endif

    while( msgrcv ( msgQueueId, (char *)&msg.mtype, MAXMESGDATA, pid, IPC_NOWAIT) > 0) {
        strcpy( ipAddr, msg.ipaddr);
        len = strlen( msg.ipaddr);
        ipAddr[len] = '\0';
        NodeId = msg.nodeId;
	 	printf("Monitor process : I have been told to monitor node %d \n",NodeId);
    }

#ifdef PRINT

    printf( " received --- %d %s \n", msg.nodeId, msg.ipaddr);

#endif

}

void  timeout()
{

#ifdef PRINT
    printf("timeout %d \n", NodeId);
#endif

    if(! live_test( ipAddr)) {
        HandleNodeFailure(NodeId);
    }
}

int main(int argc, char* argv[]) {
     CLIENT           *cl;
     char             server[ MAXHOSTNAMELEN ];
     int              num;
     void*            dum;
     static struct timeval  totaltimeout = {0, 0};

	 if(argc < 3) {
	 	printf("Insufficient number of argemnts \n");
	 	return -1;
	 }
     strcpy(ipAddr, argv[1]);
     num = strlen(argv[1]);
     ipAddr[num] = '\0';

     NodeId = atoi(argv[2]);
	 printf("Monitor process : I have been told to monitor node %d \n",NodeId);
	 	//This happens when ther is only one co-ordinator precoess in the ARC ring.
     if( !strcmp(ipAddr, "SINGLE_NODE")) {
         NodeId = -1;
     }

     if( (msgQueueId = msgget(MKEY2, PERMS | IPC_CREAT)) < 0) {
        printf(" timer can't get message queue 1 \n");
     }
		
		//Get the process identifier.
     pid = getpid();
     
	 	//Get the name of the machine and its ip-address.
     if (gethostname(server, MAXHOSTNAMELEN)) {
        error("main: gethostname: couldn't get the name of host");
     }
     
	 	//Create a handle to the local RPC server.
     if ((cl = clnt_create( server, COORDINATOR, NODE_FAILURE,"tcp")) == NULL) {
        clnt_pcreateerror(server);
        exit( CLIENT_CONNECTION_FAIL );
     }

     timerclear( &totaltimeout);

     clnt_call(cl, REGISTER_TIMER_PID, xdr_int, &pid,
            xdr_void, NULL, totaltimeout);

     signal( SIGUSR1, handler);
     signal( SIGALRM, timeout);

     while(1) {
         if( NodeId != -1) {
            alarm(TIMEOUT);
            sleep(TIMEOUT);
         }
         else {
             while(1) {
                alarm(0);
                sleep(90000000);
                if( NodeId != -1) {
                    break;
                }
             }
         }
     }
}

