/*
 *
 * dumphostsvc.c
 * BIG BROTHER DISPLAY HTML STATUS LOG
 * Robert-Andre Croteau - The MacLawran Group Inc.
 * Version 1.4
 * Mar 05th, 2000
 *
 * This program is Copyright (c) 1997-2000
 * The MacLawran Group Inc.
 * All Rights Reserved
 *
 * Take the status log and save an HTML version of it in a buffer
 *
 */


#include "bb.h"		/* THE BIG BROTHER INCLUDE FILE */
#include <errno.h>
#include <sys/stat.h>
#include <ctype.h>
#include <sys/time.h>


main(argc, argv)
int argc;       
char *argv[];
{       
struct stat statbuf;
time_t stattime;
int statres,retc,len;
char *statusdata,*hostsvcdata,*timebuf;
FILE *logfp;
char *bbhome,*bbweb;
char bbwebdir[MAXLINE];
char filemode[MAXLINE];
extern char *dohostsvc();
extern int getheader(), getfooter();

	if( argc != 3 ) {
		printf("<HTML><BODY>dumphostsvc: invalid argument</BODY></HTML>\n");
		exit(1);
	} 

	bbhome=(char *)getenv("BBHOME");
	if (bbhome) {   
		len=strlen(bbhome);
		if (len > MAXLINE - 50) {               /* CHECK THIS... */
			printf("<HTML><BODY>dumphostsvc: BBHOME is invalid - %s</BODY></HTML>\n",bbhome);
			exit(1);
		}
                sprintf(bbwebdir, "%s/web", bbhome);
        }
	else {
		printf("<HTML><BODY>dumphostsvc: BBHOME is undefined</BODY></HTML>\n");
		exit(1);
	}

	bbweb=(char *)getenv("BBWEB");
	if (bbweb == NULL) {
		printf("<HTML><BODY>dumphostsvc: BBWEB is undefined</BODY></HTML>\n");
		exit(1);
	}

	/* get file info */
	statres=stat(argv[1], &statbuf);
        if( statres == -1 ) {
		printf("<HTML><BODY>dumphostsvc: file not found - %s</BODY></HTML>\n",argv[1]);
		exit(1);
	}

	if(strlen(argv[2]) > (MAXLINE - 1) ) {
		printf("<HTML><BODY>dumphostsvc: invalid file mode - %s</BODY></HTML>\n",argv[2]);
	}

	sprintf(filemode,"%s_header",argv[2]);
	getheader(bbwebdir,filemode); 

	sprintf(filemode,"%s_footer",argv[2]);
	getfooter(bbwebdir,filemode);

	/* build buffer to receive status log */
	statusdata = (char *) calloc(1,statbuf.st_size+128);
	if( statusdata == NULL ) {
		printf("<HTML><BODY>dumphostsvc: out of memory</BODY></HTML>\n");
		exit(1);
	}	

	/* open file */
	if( (logfp = fopen(argv[1],"r")) == NULL ) {
		printf("<HTML><BODY>dumphostsvc: can't open file - %s</BODY></HTML>\n",argv[1]);
		free(statusdata);
		exit(1);
	}
	
	/* read it in */
	retc = fread(statusdata,statbuf.st_size,1,logfp);
	if ( retc != 1 || (strlen(statusdata) != statbuf.st_size)) {
		printf("<HTML><BODY>dumphostsvc: error while reading - %s</BODY></HTML>\n",argv[1]);
		free(statusdata);
		exit(1);
	}

	/* close file */
	fclose(logfp);

	/* call dohostsvc() */
	stattime = statbuf.st_ctime;
	timebuf = ctime(&stattime);
	hostsvcdata = dohostsvc(statusdata,argv[1],bbweb,bbwebdir,timebuf);

	/* display result */
	if( hostsvcdata != NULL ) {
		fwrite(hostsvcdata,strlen(hostsvcdata),1,stdout);
	}
	else {
		printf("<HTML><BODY>dumphostsvc: out of memory</BODY></HTML>\n");
		exit(1);
	}

	free(hostsvcdata);

	exit(0);
}
