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


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>


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


#define DEBUG 0


/* rewinds file fd to nearest start of line */
static void rewindtosol(FILE *fd) {
  int c;
  int iterations = 0;
  for (;;) {
    iterations++;
    if (ftell(fd) == 0) break;
    c = fgetc(fd);
    if (c == '\n') break;
    fseek(fd, -2, SEEK_CUR);
    if (iterations > 400) break; /* you never know */
  }
}


int main(void) {
  char csvbuff[128];
  char *ptrs[4];
  FILE *f;
  int i, count, csvres;
  long fsize, randpos;

  printf("i\n");

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

  if (fsize < 16) {
    printf("3ERROR: fsize too low (%ld)\n", fsize);
    fclose(f);
    return(0);
  }

  srand(time(NULL));

  count = 0;
  for (i = 0; i < 50; i++) {

    randpos = rand() % (fsize - 2);
    fseek(f, randpos, SEEK_SET);

    /* rewind back to nearest \n or start of file */
    rewindtosol(f);

    /* read entry */
    csvres = csvreadline(csvbuff, sizeof(csvbuff), ptrs, 4, f);
    if (csvres != 0) {
      if (DEBUG) printf("icsvreadline() != 0\n");
      continue;
    }
    /* ignore hosts that were offline last time I checked */
    if (atol(ptrs[2]) != 0) {
      if (DEBUG) printf("iatol(ptrs[2]) != 0 (%ld, '%s')\n", atol(ptrs[2]), ptrs[0]);
      continue;
    }
    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]);
    }
    count++;
    if (count == 5) break;
  }

  fclose(f);

  return(0);
}
