/*
  provider.c
  6/2/92 wade@mit.edu

  This program reads the pips.trans.log.provider file,
  which is created during the summary process.  It
  determines the unique providers from this file during
  a specific time period.

  optional arguments:
  V = verbose option, prints each line from the log file
      during the date range.
  U = prints only the unique providers found during the
      date range.

  if neither of the above arguments are given, only one
  line is printed with a count of the number of unique
  provider login's during the date range.

  Start date and end date are optional.  If the range is
  not specified, then the entire log file is used as the
  date range.

*/

#include <stdio.h>
#include <sys/types.h>
#include "date.h"
#include "network.h"
#include "network2.h"

struct inputrec {
  char transtype;
  char transdata[4000];
  struct daterec date;
};

#define UID_LIST_SIZE 200
#define UID_CHAR_SIZE 132

int get_nextinputrec (struct inputrec *input, FILE *infile)
{
#define TIMESTAMP_LEN 26
#define DATESTAMP_LEN 15
  char astr[4000];
  char *ptr, *ptr2;

  do {
    if (fgets (astr, sizeof(astr), infile) == NULL)
      return EOF;

    /* remove trailing LF */
    ptr2 = astr;
    *(ptr2 + strlen(astr) - 1) = NULL;

    /* copy the line to the input data field */
    strcpy(input->transdata,ptr2);

    /* null out the trailing provider uid so that the date is 
       just "Mon DD Year" */
    ptr = astr;
    *(ptr + DATESTAMP_LEN) = NULL;

    ptr = astr + 4;  /* skip over the day, e.g. "Sun" */

    if (!parse_logdate(ptr, &(input->date), 1)) {
      continue;
    }
    else
      break;
  } while (1);

  return 1;
}

dousage(char *pgm)
{
  fprintf (stderr,
	   "Usage: %s [<increment>] [<starttime>] [<endtime>]\n\
Increment must be one of H,D,W,M,Y,O (default=O)\n\
   (Hour, Day, Week, Month, or Year, or\n\
   One interval from startdate to enddate)\n\
Date & time format -- `month day [hour:minute[:second]] [year]'\n\
   E.g. 'Aug 1 1991' (quotes are needed because of embedded spaces)\n\
   Default startdate is 1st of the month, default enddate is today\n", pgm);
  exit (-1);
}

stringtolower (char *str)
{
  char *ptr;

  for (ptr = str; *ptr ; ptr++)
    if (isupper(*ptr))
      *ptr = tolower(*ptr);
}
/* test uniqueness of uid */
unique_uid(char uid_list[][UID_CHAR_SIZE], int *uid_ctr, char *uid_str) 
{
  int i, found_it;
  
  for (found_it = 0, i=0; i < UID_LIST_SIZE && i <= *uid_ctr && !found_it; i++) {
    if (!strcasecmp(uid_list[i], uid_str))
      found_it = 1;
  }

  /* if we did not find the uid, then add it to the list */
  if (!found_it && i > *uid_ctr && i < UID_LIST_SIZE) {
    strcpy(uid_list[i], uid_str);
    *uid_ctr = *uid_ctr + 1;
  }
}

/* test to see if a uid is valid */
test_owner(char *uid)
{
  char            provline[PROV_LN_SZ], *cp;
  FILE           *fopen(), *provfile;

  provfile = fopen(PROV_FILE, "r");
  if (!provfile) {
    perror(PROV_FILE);
    printf("Could not check the provider's file.\n");
    return 0;
  }

  while (fgets(provline, PROV_LN_SZ, provfile) != NULL) {
    cp = (char *) rindex(provline, ':');
    if (cp) {
      *cp = NULL;
      cp = (char *) index(provline, ':');
      if (cp) {
	if (strcasecmp(uid, ++cp) == 0) {
	  fclose(provfile);
	  return 1;
	}
      }
    }
  }
  fclose(provfile);
  return 0;

}

main (int argc, char *argv[])
{
  struct daterec startdate, enddate;
  struct daterec begof_intrvl, endof_intrvl, temp;
  struct inputrec input;
  char   increment;
  FILE  *datafile = stdin;
  int    intervalnumber;
  int    stat;
  char  *uid;
  int    uid_ctr;
  int    ctr;
  char   uid_list[UID_LIST_SIZE] [UID_CHAR_SIZE];

  if ((argv[1] != NULL && !strncmp ("-h", argv[1], 2)))
    dousage(argv[0]); /* never returns */
  
  if (argc >= 2) {
    increment = toupper ( *(argv[1]) );
    if (!index("VU", increment)) {
      fprintf (stderr, "Increment must be one of VU\n");
      exit (-21);
    }
  }
  
  if (argc < 3) { 
    setdaterec (&startdate, time(0));
    startdate.hour = startdate.minute = startdate.sec = 0;
    startdate.day = 1;
  }
  else
    parse_logdate (argv[2], &startdate, 1);
  
  if (argc < 4)  /* enddate default =  now */
    setdaterec (&enddate, time(0));
  else
    parse_logdate (argv[3], &enddate, 1);

  if (!BEFORE(startdate, enddate)) {
    fprintf (stderr, "Startdate must be before enddate\n");
    exit (-1);
  }
  
  datecpy (&begof_intrvl, startdate); /* copy startdate into begof_intrvl */
  intervalnumber = 0;
  uid_ctr = -1;

  /* skip over data which is before the startdate */
  do {
    stat = get_nextinputrec(&input, datafile);
    /* if no date was specified, start with the first date found
       in the data file */
    if (argc < 3) {
      datecpy(&startdate,input.date);
      startdate.hour = startdate.minute = startdate.sec = 0;
      datecpy(&begof_intrvl, startdate);
    }

    /* fix enddate so that it does not include records from the
       date this process is running, since any records would be
       only a partial record for this day */
    if (argc < 4) {
      datedecr(&enddate,'D');
      enddate.hour = 23;
      enddate.minute = 59;
      enddate.sec = 59;
    }

  } while ((stat != EOF) && BEFORE(input.date, startdate));

  /* okay, now input contains our first real data, so let's do something
     with it! */
  do {

    /* try to figure out what timepoint the end of interval is */
    datecpy (&endof_intrvl, enddate);

    /* gather data for current interval */
    while (!AFTER(input.date, endof_intrvl) &&
	   !BEFORE(input.date, begof_intrvl) && (stat != EOF) ) {

      /* skip over the date stuff */
      uid = input.transdata + 16;
      if (test_owner(uid)) {
	/* if needed, add this item to the unique uid list */
	unique_uid(uid_list, &uid_ctr, uid);

	if (increment == 'V')
	/* verbose option - print this item to stdout */
	  printf("%s\n",input.transdata);

	/* count the number of items printed */
	intervalnumber++;
      }

      stat = get_nextinputrec(&input, datafile);
    }

    datecpy (&begof_intrvl, endof_intrvl); /* new begof_intrvl is endof intv */
  }
  while (BEFORE(begof_intrvl, enddate));

  if (increment == 'U') {
    /* print the unique providers */
    printf("\nThe unique provider login's:\n");
    for(ctr=0; ctr <= uid_ctr; ctr++)
      printf("%s\n",uid_list[ctr]);
  }

  if (intervalnumber == 0)
    printf("There were no provider login's during this date range.\n");
  else
    printf("\nThere were %d unique login's during this date range.\n", ++uid_ctr);

}



