/*
 * OGUP servers list gophermap
 *
 * Copyright (C) 2019 Mateusz Viste
 */


#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>


#include "../../cmods/csv.c"


unsigned long getcount(const char *fname, time_t *modtime, char *errstr, unsigned long *countactive, unsigned long *countpending, unsigned long *countdown) {
  FILE *f;
  unsigned long count;
  char buff[64];
  char *ptrs[4];
  struct stat sb;

  f = fopen(fname, "rb");
  if (f == NULL) {
    sprintf(errstr, "failed to open db file");
    return(0);
  }
  if (fstat(fileno(f), &sb) != 0) {
    fclose(f);
    sprintf(errstr, "fstat() failed on db count file");
    return(0);
  }
  *modtime = sb.st_mtime;
  csvreadline(buff, sizeof(buff), ptrs, 4, f);
  fclose(f);
  count = atol(ptrs[0]);
  *countactive = atol(ptrs[1]);
  *countpending = atol(ptrs[2]);
  *countdown = atol(ptrs[3]);

  if (count == 0) sprintf(errstr, "empty db");

  return(count);
}


int main(void) {
  unsigned long count, countactive, countpending, countdown;
  time_t lastupdate;
  struct tm *lastupdatetm;
  char errstr[64];
  char csvbuff[128];
  char *ptrs[4];
  FILE *f;
  int i;

  printf("i\n");

  count = getcount("../ogupdb.cnt", &lastupdate, errstr, &countactive, &countpending, &countdown);
  lastupdatetm = gmtime(&lastupdate);

  if (count == 0) {
    printf("3ERROR: %s\n", errstr);
  } else {
    printf("iThe Observable Gopherspace Universe Project knows about:\n"
           "i%5lu servers total, of which:\n"
           "i%5lu have been validated as operational\n"
           "i%5lu are down\n"
           "i%5lu are pending validation\n"
           "i\n"
           "iLast update: %04d-%02d-%02d %02d:%02d UTC\n", count, countactive, countdown, countpending, lastupdatetm->tm_year + 1900, lastupdatetm->tm_mon + 1, lastupdatetm->tm_mday, lastupdatetm->tm_hour, lastupdatetm->tm_min);
  }

  printf("i\n");

  f = fopen("../ogupdb.dat", "rb");
  if (f == NULL) {
    printf("3ERROR: fopen() failure\n");
    return(0);
  }

  for (;;) {
    i = csvreadline(csvbuff, sizeof(csvbuff), ptrs, 4, f);
    if (i != 0) break;
    if (atol(ptrs[2]) != 0) continue; /* ignore hosts that were offline last time I checked */
    if (atol(ptrs[1]) != 70) {
      printf("1%s:%s\t\t%s\t%s\n", ptrs[0], ptrs[1], ptrs[0], ptrs[1]);
    } else {
      printf("1%s\t\t%s\t%s\n", ptrs[0], ptrs[0], ptrs[1]);
    }
  }

  fclose(f);

  printf("i\ni--- [EOF] -----------------------------\n");

  return(0);
}
