/* Author: Ram Samudrala (me@ram.org)
 * Version: O1.1
 * Detail: <http://www.ram.org/computing/plan/plan.html>
 * May 16, 1993.
 *
 * See the URL above for more information.
 *
 * planedit.c:  This edits your planfile on request, but is usually
 *              supposed to be used each time you log in or log out.
 *              See usage for details.   Randomisation is performed
 *              by taking the second modulus number of quotes.
 *
 * Usage:       planedit plan-file i|o [number of quotes]
 *
 * V1.1: November 30, 1994. Made it so it would also list the hostname 
 *       you're on.  This was suggested by Jason Smith (smithj4@rpi.edu).
 *
 */

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

#define in 'i'
#define IN 'I'

#ifdef VMS
#define FOPEN(filename, specif) fopen(filename, specif, "ctx=rec", "mrs=50000", "rat=cr", "rfm=var")
#else
#define FOPEN(filename, specif) fopen(filename, specif)
#endif

#include "plan.h"

void quote_plan(FILE *plan_fp, int num_quotes);

/******************************************************************/

int main(int argc, char *argv[])
{
  char hostname[32], line[MAX_LINE_LENGTH];
  FILE *plan_fp, *original_plan_fp;
  time_t tp;
  
  if ((argc < 3)  || argc > 4)
    {
      fprintf(stderr, "Usage: %s plan-file i|o [number of quotes]\n", argv[0]);      
      return 0;
    }
  
#ifdef VMS
  remove(argv[1]);
#endif

  if ((plan_fp = FOPEN(argv[1], "w")) == NULL)
    {
      fprintf(stderr, "%s: couldn't open %s for writing!\n", argv[0], PLAN_FILE);
      return 0;
    }

  if ((original_plan_fp = FOPEN(ORIGINAL_PLAN_FILE, "r")) == NULL)
    {
      fclose(plan_fp);
      fprintf(stderr, "%s: couldn't open %s for reading!\n", argv[0], ORIGINAL_PLAN_FILE);
      return 0;
    }
  
  gethostname(hostname, sizeof(hostname));
  tp = time(NULL);
  if ((argv[2][0] == in) || (argv[2][0] == IN))
     fprintf(plan_fp, "On %s since %s\n", hostname, ctime(&tp));
  else
    fprintf(plan_fp, "Last seen on %s at %s\n", hostname, ctime(&tp));

  while(fgets(line, MAX_LINE_LENGTH, original_plan_fp))
    fprintf(plan_fp, "%s", line);
  fclose(original_plan_fp);

  if (argc == 4)
    if (atoi(argv[3]) > 0)
      quote_plan(plan_fp, atoi(argv[3]));
  fclose(plan_fp); 
  
  return 1;
}

/******************************************************************/

void quote_plan(FILE *plan_fp, int num_quotes)
{
  char line[MAX_LINE_LENGTH];
  FILE *quotes_fp;
  
  sprintf(line, "%s%ld", QUOTES_FILE_PREFIX, (time(NULL) % num_quotes));  
  if ((quotes_fp = fopen(line, "r")) == NULL)
    return;  
  while (fgets(line, MAX_LINE_LENGTH, quotes_fp))
    fprintf(plan_fp, "%s", line);
  fprintf(plan_fp, "\n");
  fclose(quotes_fp);
  return;
}

/******************************************************************/
