#include "netwatch.h"
#include <syslog.h>
#include <stdio.h>

static FILE *tmpfp;
static char tmpname[256];
static char command[256];
static char warnto[256] = { 0 };
extern int mailflag;
extern int syslogflag;
extern char *version;
extern char userwarn[];

void printbuf(FILE *fp, unsigned char *buf)
{
	int i;
	/* Dump HEader */
	for (i=0;i<60;i++)
	{
		fprintf(fp," %2X",buf[i]);
		if (syslogflag) syslog(LOG_ALERT," %2X",buf[i]);
		if (i && !(i%16))
		{
			fprintf(fp,"\n");
			if (syslogflag) syslog(LOG_ALERT,"\n");
		}
	}
	fprintf(fp,"\n");
	if (syslogflag) syslog(LOG_ALERT,"\n");
	

}

void warning(char s[], unsigned char *buf)
{
	time_t dt;

	dt = time(0);
	tmpnam(tmpname);
	tmpfp = fopen(tmpname,"w");
	if (tmpfp)
	{
		fprintf(tmpfp,"******************************************\n");
		fprintf(tmpfp,"WARNING MESSAGE from Netwatch %s at %s\n",
			version,ctime(&dt));
		fprintf(tmpfp,"%s\n",s);
		if (syslogflag) syslog(LOG_ALERT,"%s\n",s);
		if (buf)
		{
			printbuf(tmpfp,buf);
		}
		fprintf(tmpfp,"******************************************\n");
		fclose(tmpfp);
		if (!warnto[0])
			strcpy(warnto,userwarn);
		if (warnto[0])
		{
			sprintf(command,"mail %s < %s&",warnto,tmpname);
			system(command);
		}
		unlink(tmpname);
	}
}
