#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>

int sockfd;
int timedout;

void timeout ()
  {
  timedout=1;
  close (sockfd);
  }

int check (int port, uint32_t addr)
  {
  struct sockaddr_in sa;
  int retcode=0;

  sa.sin_family = AF_INET;
  sa.sin_port = htons (port);
  sa.sin_addr.s_addr=addr;

  sockfd = socket (PF_INET, SOCK_STREAM, 0);
  timedout=0;
  signal (SIGALRM, timeout);
  alarm(10);
  if (connect(sockfd, (struct sockaddr *) (&sa), sizeof (sa)))
    {
    if (timedout)
      errno = ETIMEDOUT;
    syslog(LOG_USER|LOG_CRIT,"Could not connect: %m");
    retcode=1;
    }
  signal (SIGALRM, SIG_IGN);
  alarm (0);
  close (sockfd);
  return (retcode);
  }


int main(int argc, char *argv[])
  {
  char *tty;
  int port;
  uint32_t addr;
  struct hostent *hostent;
  int fd;

  if (argc < 4)
    {
    fprintf (stderr,"checkrouter serial_device host port\n");
    return 1;
    }
  tty=argv[1];
  fd=open (tty,O_RDONLY);
  if (fd==-1)
    fprintf (stderr,"Could not open the serial device\n");
  else
    {
    port=atoi(argv[3]);
    hostent=gethostbyname(argv[2]);
    if (hostent)
      {
      addr=*(uint32_t *)hostent->h_addr_list[0];
      close (0);	// close FDs no longer used
      close (1);
      close (2);
      do
        {
        sleep (120);	// time for the router to reboot and start rechecking
        while (!check(port,addr))
          sleep(60);	// time between checks
        close(fd);	// reset
        sleep (1);
        }
      while ((fd=open (tty,O_RDONLY))!=-1);
      syslog (LOG_USER|LOG_CRIT,"Could not open the serial device, exiting: %m");
      }
    else
      fprintf (stderr,"Host not found\n");
    }
  return 1;
  }
