/*
    Take a file of "? domain.com" lines and generate a fast hash file
    in which to look them up.
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#ifndef MAX_LINE
#define MAX_LINE 4097
#endif

/* TEMPORARY: extremely crude argument parsing while knocking up prototype */
int main(int argc, char **argv)
{
  FILE *rawhashfile = fopen("/tmp/rawhashdata", "w");
  FILE *infile = fopen(argv[1], "r");
  char line[MAX_LINE];
  char defscore[MAX_LINE];

  if (infile == NULL) {
    fprintf(stderr, "syntax: fastmap RULEFILE\n");
    if (rawhashfile != NULL) fclose(rawhashfile);
    exit(1);
  }
  if (rawhashfile == NULL) {
    fprintf(stderr, "fastmap: cannot open /tmp/rawhashfile\n");
    if (infile != NULL) fclose(infile);
    exit(1);
  }
  for (;;) {
    char *s;
    line[MAX_LINE-1] = '\0';
    s = fgets(line, MAX_LINE-1, infile);
    if (s == NULL) break;
    if (feof(infile)) break;
    if (ferror(infile)) break;
    s = strchr(line, '\r'); if (s != NULL) *s = '\0';
    s = strchr(line, '\n'); if (s != NULL) *s = '\0';
    s = strchr(line, '\r'); if (s != NULL) *s = '\0';
    if (*line == '\0') continue;
    switch(line[0]) {
    case '#':
      continue;
    case '*':
      if (line[1] == ' ') {
        strcpy(defscore, line+2);
      }
      continue;
    case '?':
    case '=':
      if (line[1] == ' ') {
        char *s = line+2;
        for (;;) {
          if (*s == '\0') break;
          if (isalpha(*s) && isupper(*s)) *s = tolower(*s);
          s += 1;
	}
        fprintf(rawhashfile, "%s %s\n", line+2, defscore);
      }
      continue;
    default:
      fprintf(stderr, "fastmap: Illegal entry '%s'\n", line);
      exit(1);
    }
  }
  fclose(infile);
  fclose(rawhashfile);
  sprintf(line, "makemap hash %s.db < /tmp/rawhashdata", argv[1]);
  fprintf(stderr, "Executing '%s'\n", line);
  system(line);
  exit(0);
  return(1);
}
