
/*
 * Copyright (c) 2001 BBNT Solutions LLC
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for any purpose is hereby granted without
 * fee, provided that the above copyright notice and this permission
 * appear in all copies and in supporting documentation, and that the
 * name of BBN Technologies not be used in advertising or publicity
 * pertaining to distribution of the software without specific,
 * written prior permission.  BBN makes no representations about the
 * suitability of this software for any purposes.  It is provided "AS
 * IS" without express or implied warranties.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stats.h"

char *script_file = NULL;
FILE *sfp = NULL;

void script_open ()
{
    char *scripts_dir, *next;
    char full_script [BUFFER_SIZE];

    if ((sfp = fopen (script_file,"r")) != NULL)
	return;
    else if (strchr (script_file,'/') != NULL)
    {
	fprintf (stderr,"cannot open script: %s\n", script_file);
	exit (1);
    }
    scripts_dir = getenv ("STATS_SCRIPTS");
    next = strtok (scripts_dir,":");
    while (next != NULL)
    {
	strcpy (full_script,next);
	strcat (full_script,"/");
	strcat (full_script,script_file);
	if ((sfp = fopen (full_script,"r")) != NULL)
	    return;
	next = strtok (NULL,":");
    }
    if (sfp == NULL)
    {
	fprintf (stderr,"cannot open script: %s\n", script_file);
	exit (1);
    }
}


void script_close ()
{
    fclose (sfp);
}


unsigned short all_whitespace (line)
char *line;
{
    char *p = line;

    while (*p != '\0')
    {
	if ((*p != '\n') && (*p != ' ') && (*p != '\t'))
	    return (FALSE);
	p++;
    }
    return (TRUE);
}


void script_proc ()
{
    char cmd [MAX_LINE];

    script_open ();
    while (fgets (cmd,MAX_LINE,sfp) != NULL)
    {
	cmd [strlen (cmd) - 1] = '\0';
	if ((cmd [0] != '#') && !all_whitespace (cmd))
	    do_cmd (cmd);
    }
    script_close ();
}
