/*
 * $Id: mkso.c,v 1.1 1997/01/21 15:34:02 gdr Exp $
 *
 * Devin Reade, 1997.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#define BUFFERSIZE 1024
#define DELIM " \t"

char *progname = NULL;
int deleteFiles = 0;
int verbose = 0;

void
usage (void) {
  printf("This program is part of the GNO installation package.\n");
  printf("It creates .so (nroff source files) for the man package\n\n");
  printf("Usage: %s [-dhv] datafile\n", progname);
  printf("\t-h\tprint usage information\n");
  printf("\t-d\tdelete instead of create files (safe)\n");
  printf("\t-v\tverbose operation\n");
  exit(1);
}

int main(int argc, char **argv) {
  static char dataBuffer[BUFFERSIZE];
  static char magicBuffer[BUFFERSIZE];
  FILE *fp, *outfp;
  char *p, *file, *new, *org;
  int line = 0;
  int c;
  char *magic = ".\\\" This file is auto-generated by mkso.\n";

  progname = argv[0];
  while ((c = getopt(argc, argv, "dhv")) != EOF) {
    switch (c) {
    case 'd':
      deleteFiles = 1;
      break;
      
    case 'v':
      verbose = 1;
      break;

    case 'h':
    default:
      usage();
    }
  }
  if (argc - optind != 1) {
    usage();
  } else {
    file = argv[optind];
  }

  if ((fp = fopen(file, "r")) == NULL) {
    perror("couldn't open data file");
    exit(1);
  }

  while (fgets(dataBuffer, BUFFERSIZE, fp) != NULL) {
    line++;

    /* eliminate comments and newlines -- get file names */
    if ((p = strchr(dataBuffer, '#')) != NULL ||
	(p = strchr(dataBuffer, '\n')) != NULL) {
      *p = '\0';
    }
    if ((org = strtok(dataBuffer, DELIM)) == NULL) {
      continue;
    }
    if ((new = strtok(NULL, DELIM)) == NULL) {
      fprintf(stderr, "missing new file name at line %d of %s", line, file);
      continue;
    }

    if (deleteFiles) {
      if ((outfp = fopen(new, "r")) == NULL) {
	/* file doesn't exist -- doesn't need deleting */
	continue;
      }
      
      /* look for magic string on second line */
      if (fgets(magicBuffer, BUFFERSIZE, outfp) == NULL ||
	  fgets(magicBuffer, BUFFERSIZE, outfp) == NULL ||
	  strcmp(magicBuffer, magic)) {
	printf("bad magic for %s -- not deleted\n", new);
      } else {
	if (verbose) {
	  printf("rm -f %s\n", new);
	}
	unlink(new);
      }
    } else {

      if (access(new, F_OK) == 0) {
	if (verbose) {
	  printf("file %s already exists -- skipping\n", new);
	}
	continue;
      }

      if (verbose) {
	printf("linking %s to %s\n", new, org);
      }

    
      if ((outfp = fopen(new, "w")) == NULL) {
	fprintf(stderr,
		"couldn't open \"%s\" from line %d: %s: file skipped\n",
		new, line, strerror(errno));
	continue;
      }
      fprintf(outfp, ".so %s\n", org);
      fprintf(outfp, magic);
      fclose(outfp);
    }
  }

  if (ferror(fp)) {
    perror("error on reading data file");
    exit(1);
  }

  fclose(fp);
  return 0;
}
