/* Vorlesung Verteilte Systeme I
   Sommersemester 1999
   Musterloesung zum Uebungsblatt 2, Aufgabe 2
   Cookie-Server zur Auswahl eines Cookies aus einer Datei
   Joerg Hakenberg 26.4.1999 */
/* Compilieren mit
     export LD_LIBRARAY_PATH=/usr/ucblib
     cc -o x x.c -I/usr/ucbinclude -L/usr/ucblib -lucb
*/

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

#define REQUESTPIPE "reqpipe"
#define RESPONSEPIPE "respipe"

/* Format der Cookie-Datei : Ein Spruch pro Zeile */
#define COOKIE "cookies.txt"

int main (int argc, char**argv) {

  int ret;
  /* Pipe - IO-Stream */
  FILE* reqpipe;
  FILE* respipe;
  /* Request-Puffer */
  char buffer[128];

  /* Vars fuer Cookie */
  FILE* datei;
  char cookie[128];
  int i, j, lines;

  /* Anlegen der Pipes */
  puts("creating pipes");
  unlink(REQUESTPIPE);
  unlink(RESPONSEPIPE);
  ret = mknod(REQUESTPIPE, S_IFIFO | S_IRWXU,  NULL);
  if (ret == -1) {
    perror("can't create request pipe");
    exit(1);
  }
  ret = mknod(RESPONSEPIPE, S_IFIFO | S_IRWXU, NULL);
  if (ret == -1) {
    perror("can't create response pipe");
    exit(1);
  }

  /* Pipe zum Schreiben und Lesen oeffnen */
  puts("opening pipes");
  reqpipe = fopen(REQUESTPIPE, "r+");
  if (reqpipe == NULL) {
    perror("can't open requestpipe");
    close(reqpipe);
    unlink(REQUESTPIPE);
    exit(1);
  }
  respipe = fopen(RESPONSEPIPE, "r+");
  if (respipe == NULL) {
    perror("can't open response pipe");
    close(respipe);
    unlink(RESPONSEPIPE);
    exit(1);
  }

  while (1) {

    /* Anfrage lesen */
    puts("reading request ...");
    fgets(buffer, sizeof(buffer), reqpipe);
    if (ferror(reqpipe)) {
      perror("error reading request pipe");
      close(reqpipe);
      unlink(REQUESTPIPE);
      exit(1);
    } else if (feof(reqpipe)) {
      close(reqpipe);
      unlink(REQUESTPIPE);
      exit(1);
    }
    printf("Request is : %s", buffer);

    /* zufaellig einen Cookie aus der Datei COOKIE auswaehlen */
    datei = fopen(COOKIE, "r");
    lines = 0;
    while (fgets(cookie, 150, datei)) {
        lines++;
    }
    rewind(datei);
    i = 1 + (int) ((float)lines * rand() / (RAND_MAX + 1.0));
    for (j = 1; j <= i; j++) {
        fgets(cookie, 150, datei);
    }
    fclose(datei);

    /* Antwort schreiben */
    puts("writing response");
    fprintf(respipe, cookie);
    fflush(respipe);

  }

}
