#include <stdio.h>
#include <strings.h>
#include <errno.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>

void main(int c, char **argv)
{
  int avail, lost_connection, closedir();
  char *strerror();
  DIR *pdir;
  struct dirent *pdent, *readdir();
  FILE *fptr;
  void log_print_date_time();
  avail = 0;
  lost_connection = 0;
  fptr = fopen(argv[2], "w");
  while (1)
  {
    if (avail == 0)
    {
      pdir = opendir(argv[1]);
      if (pdir != NULL)
      {
        avail = 1;
      }
    }
    if (avail == 1)
    {
      pdent = readdir(pdir);   /* current directory .  */
      if (pdent != NULL)
      {
        if (lost_connection == 1)
        {
          lost_connection = 0;
          log_print_date_time(fptr);
          fprintf(fptr, "Share available again\n ");
          fflush(fptr);
        }
        pdent = readdir(pdir);  /* One directory higher ..  */
        if (pdent != NULL)
        {
          pdent = readdir(pdir); /* first file in current direcctory  */
        }
        else
        {
          if (lost_connection == 0)
          {
            avail = 0;
            lost_connection = 1;
            log_print_date_time(fptr);
            fprintf(fptr, "Error %d %s\n ", errno, strerror(errno));
            fflush(fptr);
          }
        } 
      }
      else
      {
        if (lost_connection == 0)
        {
          avail = 0;
          lost_connection = 1;
          log_print_date_time(fptr);
          fprintf(fptr, "Error %d %s\n ", errno, strerror(errno));
          fflush(fptr);
        }
      }
    }
    sleep(3);
    rewinddir(pdir);
  }
  closedir(pdir);
  fclose(fptr);
}

void log_print_date_time(FILE *fptr)
{
  time_t ctime;
  struct tm tim;
  ctime = time(NULL);
  tim = *localtime(&ctime);
  fprintf(fptr, "%d-%02d-%02d %02d:%02d:%02d ", tim.tm_year + 1900, tim.tm_mon + 1, tim.tm_mday, tim.tm_hour, tim.tm_min, tim.tm_sec);
}
