#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 "System.h"
#include "StatePublisher.h"
#include "Syslog.h"
//
////////////////////////////////////////////////////////////////////////////////
//
// PURPOSE:  To start up the SonardyneDriver driver task.
// AUTHOR:   Rich Henthorn
// DATE:     02/07/07
// COMMENTS: 
//
////////////////////////////////////////////////////////////////////////////////
//
//

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

StatePublisher *publisher = 0;

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

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

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

  try {
    sleep(1); // give some time to get things started ... 
    publisher = new StatePublisher();
    publisher->setVerbose(verbose);
    if (0 == publisher->init())
    {
      publisher->run();
    }
    else
      exit(0);
  }
  catch (Exception e) {
    Syslog::write("%s - caught Exception: %s\n", argv[0], e.msg);
  }
  catch (...) {
    Syslog::write("%s - caught unknown exception\n", argv[0]);
  }

  delete publisher;

  return 0;

}

void ignorePipe(int signalNo) {
  // For now just display a message may be better in the future to close the socket
  Syslog::write("SatePublisher : pipe is broken\n");
}


void signalHandler(int signalNo)
{

  //  cleanup();
  exit(0);
}

void cleanup()
{
  delete publisher;
}
