#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <unix.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h> // IO Control of socket.
#include "LayeredControlIF.h"
#include "System.h"
#include "VcsServer.h"
#include "Syslog.h"
//
////////////////////////////////////////////////////////////////////////////////
//
// PURPOSE:  To start up the VcsServer task.
// AUTHOR:   Rich Henthorn
// DATE:     02/07/07
// COMMENTS: 
//
////////////////////////////////////////////////////////////////////////////////
//
//

void signalHandler(int signalNo);
void cleanup();

VcsServer *Server = 0;

int main( int argc, char **argv )
{

  signal(SIGINT,  signalHandler);
  signal(SIGTERM, signalHandler);
  signal(SIGQUIT, signalHandler);
  atexit(cleanup);
  // Set task priority
  if (System::setTaskPriority(NonCriticalDriverPriority) == -1)
    return 1;

  Boolean verbose = False;
  Boolean sim = False;
  for (int i = 1; i < argc; i++) {
    if (!strcmp(argv[i], "-v")) 
      verbose = True;
    else if (!strcmp(argv[i], "-sim")) 
      sim = True;
  }

  try {
    Server = new VcsServer(sim, verbose);
    if (0 == Server->init())
    {
      Syslog::write("running Server");
      Server->run();
    }

  }
  catch (Exception e) {
    Syslog::write("%s - caught Exception: %s\n", argv[0], e.msg);
  }
  catch (...) {
    Syslog::write("%s - caught unknown exception\n", argv[0]);
  }

  Syslog::write("%s - sleeping to let LayeredControl run its abort plan", argv[0]);
  sleep(36000);

  return 0;

}


void signalHandler(int signalNo)
{

  cleanup();
  exit(0);
}

void cleanup()
{
  if (Server)
  {
    delete Server;
    Server = 0; 
 }
}
