/*
 * OGUP main gophermap
 *
 * Copyright (C) 2019 Mateusz Viste
 */


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


unsigned long getcount(const char *fname, time_t *modtime, char *errstr) {
  FILE *f;
  unsigned long count;
  char buff[32];
  int i;
  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) {
    sprintf(errstr, "fstat() failed on db count file");
    return(0);
  }
  *modtime = sb.st_mtime;
  i = fread(buff, 1, sizeof(buff) - 1, f);
  fclose(f);
  if (i < 1) {
    sprintf(errstr, "empty count file");
    return(0);
  }
  buff[i] = 0;
  count = atol(buff);

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

  return(count);
}


int main(void) {
  unsigned long count;
  time_t lastupdate;
  struct tm *lastupdatetm;
  char errstr[64];

  printf("i\n"
         "i          Observable Gopherspace Universe Project\n"
         "i\n"
         "iWelcome to the gopher site of the Observable Gopherspace Universe\n"
         "iProject (OGUP)! The OGUP is about maintaining and publishing an\n"
         "iindependent list of servers available in the gopherspace.\n"
         "i\n"
         "1List of servers\tlist\n"
         "1Show 5 random servers\trnd\n"
         "1Recently down servers\tdown\n"
         "1About the OGUP\tabout\n"
         "1Support the project!\tsupport\n"
         "i\n");

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

  if (count == 0) {
    printf("3ERROR: %s\n", errstr);
  } else {
    printf("iAs of %04d-%02d-%02d, the OGUP knows about %lu servers.\n", lastupdatetm->tm_year + 1900, lastupdatetm->tm_mon + 1, lastupdatetm->tm_mday, count);
  }

  return(0);
}
