/* prochist.c -- Process the history file, where it keeps the old summary
 *               from "The Epoc".
 *
 * This file is part of TUA.
 * 
 *   Copyright (C) 1991,96  Lele Gaifax
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the license, or (at
 *   your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 */

#include "tua.h"

#define NotZero(rec)	\
    ((rec).Out.Files || (rec).In.Files || (rec).Out.Bytes || (rec).In.Bytes || \
	(rec).Out.Time || (rec).In.Time)

char TheEpoc[30] = {0};
static char TheLastOne[30] = {0};

/*
 * The history file is kept in ascii form, so anybody can easily alter
 * it. The first line is the date we began to play, the second one the
 * date of the last update. Then, in alphabetic order, the systems and
 * all the field of the system_history structure.
 */

/*
 * Read a line from file, skipping comments, that begins with a '#'
 */

static char *
DEFUN (ReadALine, (file, where, lenght),
       FILE * file AND
       char where[] AND
       int lenght)
{
  char *status;
  char buffer[256];
  do
    {
      status = fgets (buffer, sizeof (buffer), file);
    }
  while (status != NULL && (buffer[0] == '#' || buffer[0] == '\n'));
  
  strncpy (where, buffer, lenght);
  return status;
}

int
DEFUN_VOID (read_system_history)
{
  extern int EXFUN(access, (CONST char *, int));
  char pathname[LPNMAX];
  char buffer[256];
  FILE *FileHist;
  CONST char * history_filename;

#if BOTH_OF_THEM  
  history_filename = (is_taylor_uucp ? TAYLOR_HISTORY : HDB_HISTORY);
#else
#if TAYLOR_UUCP
  history_filename = TAYLOR_HISTORY;
#else
  history_filename = HDB_HISTORY;
#endif /* TAYLOR_UUCP */
#endif /* BOTH_OF_THEM */

  sprintf (pathname, "%s/%s", logs_prefix_path_opt, history_filename);
  if (access (pathname, 0))
    return (OK);
  if ((FileHist = fopen (pathname, "r")) == (FILE *) NULL)
    {
      LOG ("cannot open %s", pathname);
      return ERROR;
    }
  if (ReadALine (FileHist, TheEpoc, sizeof (TheEpoc)) == NULL ||
      ReadALine (FileHist, TheLastOne, sizeof (TheLastOne)) == NULL)
    {
      LOG ("%s is not a valid history file", pathname);
      return ERROR;
    }

  while (ReadALine (FileHist, buffer, sizeof (buffer)) != NULL && *buffer != '%')
    {
      system_rec_t *sr;
      moved_stuff_t ms_in, ms_out;
      char sys[20];

      if (sscanf (buffer, "%s %u %u %lf %lf %lf %lf",
		  sys,
		  &ms_out.Files, &ms_in.Files,
		  &ms_out.Bytes, &ms_in.Bytes,
		  &ms_out.Time, &ms_in.Time) != 7)
	{
	  LOG ("%s is not a valid history file", pathname);
	  return ERROR;
	}

      if (just_some_system_opt &&
	  (search_system (sys) == (system_rec_t *) NULL))
	continue;

      sr = insert_system (sys);
      sr->History.Out = ms_out;
      sr->History.In  = ms_in;
    }
  if (*buffer == '%')		/* If there is a line beginning with '%'
                                 * then there is the monthly data too */
    {
      while (ReadALine (FileHist, buffer, sizeof (buffer)) != NULL)
	{
	  system_rec_t *sr;
	  char sys[20];
	  double monthly_data[12];
	  int idx, last_month;

	  if (sscanf (buffer, "%s %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %d",
		      sys, &monthly_data[0], &monthly_data[1],
		      &monthly_data[2], &monthly_data[3],
		      &monthly_data[4], &monthly_data[5],
		      &monthly_data[6], &monthly_data[7],
		      &monthly_data[8], &monthly_data[9],
		      &monthly_data[10], &monthly_data[11],
		      &last_month) != 14)
	    {
	      LOG ("%s is not a valid history file", pathname);
	      return ERROR;
	    }

	  if (just_some_system_opt &&
	      (search_system (sys) == (system_rec_t *) NULL))
	    continue;

	  sr = insert_system (sys);
	  for (idx = 0; idx <= 11; idx++) 
	    sr->History.MonthlyActivity[idx] = monthly_data[idx];
	  sr->History.LastMonthProcessed = last_month;
	}
    }
  else
    return ERROR;
  fclose (FileHist);
  return (OK);
}

static FILE *FileHist;

static void
DEFUN (WriteSysHist, (sys),
       CONST system_rec_t * sys)
{
  if (NotZero (*sys) || NotZero (sys->History))
    {
      fprintf (FileHist, "%s %u %u %f %f %f %f\n",
	       sys->System,
	       sys->History.Out.Files + sys->Out.Files,
	       sys->History.In.Files + sys->In.Files,
	       sys->History.Out.Bytes + sys->Out.Bytes,
	       sys->History.In.Bytes + sys->In.Bytes,
	       sys->History.Out.Time + sys->Out.Time,
	       sys->History.In.Time + sys->In.Time);
    }
}

static void
DEFUN (WriteSysHistResetting, (sys),
       CONST system_rec_t * sys)
{
  if (NotZero (*sys))
    fprintf (FileHist, "%s %u %u %f %f %f %f\n",
	     sys->System, sys->Out.Files, sys->In.Files, sys->Out.Bytes,
	     sys->In.Bytes, sys->Out.Time, sys->In.Time);
}

static void
DEFUN (WriteMonthlyData, (sys),
       CONST system_rec_t * sys)
{
  if (NotZero (*sys) || NotZero (sys->History))
    {
      int idx;
      fprintf (FileHist, "%s", sys->System);
      for (idx = 0; idx <= 11; idx++)
	fprintf (FileHist, " %.2f", sys->History.MonthlyActivity[idx]);
      fprintf (FileHist, " %d\n", sys->History.LastMonthProcessed);
    }
}

int
DEFUN (write_system_history, (reset),
       int reset)
{
  char pathname[LPNMAX];
  traverse_func_t write_funct;
  CONST char * history_filename;

#if BOTH_OF_THEM  
  history_filename = (is_taylor_uucp ? TAYLOR_HISTORY : HDB_HISTORY);
#else
#if TAYLOR_UUCP
  history_filename = TAYLOR_HISTORY;
#else
  history_filename = HDB_HISTORY;
#endif /* TAYLOR_UUCP */
#endif /* BOTH_OF_THEM */

  sprintf (pathname, "%s/%s", logs_prefix_path_opt, history_filename);
  
  if ((FileHist = fopen (pathname, "w")) == (FILE *) NULL)
    {
      LOG ("cannot open %s", pathname);
      return ERROR;
    }
 /*
   * If I have to reset the history, the initial date become the
   * date of the last update, while this one become the current
   * date. Otherwise update only the last one.
   */

  fputs ("#\n\
# This is the history file for TUA, created automatically.\n\
# It should't be edited by hand. Anyway (;-)), there must be no empty lines,\n\
# and the number of fields must be 7 for the historical section, 14 for the\n\
# monthly one, separated with blanks.\n\
# After the historical data, there is a line with a single '%' char at the\n\
# beginning, and next the monthly summary, system by system.\n\
#\n\
# system-name  fileout  filein  byteout  bytein  Out.Time  In.Time\n\
#\n", FileHist);
  if (reset)
    {
      fprintf (FileHist, "%s", (*TheLastOne ? TheLastOne : Since));
      if (!*TheLastOne)
	fprintf (FileHist, "\n");
      fprintf (FileHist, "%s\n", julian_to_asc (StatEndingTime));
    }
  else
    {
      fprintf (FileHist, "%s", (*TheEpoc ? TheEpoc : Since));
      if (!*TheEpoc)
	fprintf (FileHist, "\n");
      fprintf (FileHist, "%s\n", julian_to_asc (StatEndingTime));
    }

  if (reset)
    write_funct = (traverse_func_t) WriteSysHistResetting;
  else
    write_funct = (traverse_func_t) WriteSysHist;
  
  enquire_systems (write_funct);
  
  fputs ("%\n", FileHist);
  enquire_systems ((traverse_func_t) WriteMonthlyData);
  fclose (FileHist);
  return OK;
}
