/*
 * OGUP "recently down" 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"


static char *howold(long s) {
  static char buf[64];
  if (s < 120) {
    sprintf(buf, "%ld seconds", s);
  } else if (s < 3600) {
    sprintf(buf, "%ld minutes", s / 60);
  } else if (s < 7200) {
    sprintf(buf, "%ld h and %ld minutes", s / 3600, (s % 3600) / 60);
  } else if (s < 172800) {
    sprintf(buf, "%ld hours", s / 3600);
  } else {
    sprintf(buf, "%ld days", s / 86400);
  }
  return(buf);
}


static char *printtime(struct tm *t) {
  static char buf[64];
  sprintf(buf, "%d-%02d-%02d %02d:%02d", t->tm_year + 1900, t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min);
  return(buf);
}


int main(void) {
  time_t now, then;
  struct tm *t;
  char csvbuff[128];
  char *ptrs[4];
  char serv[32];
  long downcount = 0;
  FILE *f;

  printf("i\n"
         "iThis page lists gopherspace nodes that have been observed by the OGUP to\n"
         "icollapse recently. All timestamps are given in terran UTC time.\n"
         "i\n");

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

  now = time(NULL);
  for (;;) {
    char *howlongago;
    int i = csvreadline(csvbuff, sizeof(csvbuff), ptrs, 4, f);
    if (i != 0) break;
    then = atol(ptrs[2]);
    if (then <= 1) continue;
    howlongago = howold(now - then);
    t = gmtime(&then);
    if (atol(ptrs[1]) != 70) {
      snprintf(serv, sizeof(serv), "%s:%s", ptrs[0], ptrs[1]);
    } else {
      snprintf(serv, sizeof(serv), "%s", ptrs[0]);
    }
    printf("i%-24s went down %s ago (%s)\n", ptrs[0], howlongago, printtime(t));
    downcount++;
  }

  fclose(f);

  if (downcount == 0) {
    printf("iNothing to list! All known gopherspace servers seem healthy.\n");
  }

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

  return(0);
}
