#ifndef lint
static char *RCSid = "$Header: log.c,v 1.8 89/10/16 20:22:49 mr-frog Exp $";
#endif

/*
 * log.c
 *
 * Log an empire error to a file.
 *
 * Dave Pare, 1989
 */

#include "misc.h"
#include <errno.h>
#include <fcntl.h>
#include <varargs.h>
#include <stdio.h>
#include "deity.h"

static	char *logfile;

/*
 * Points logfile at datadir/"program".log
 */
loginit()
{
	extern	char *program;
	extern	char datadir[];
	char	buf[1024];

	sprintf(buf, "%s/%s.log", datadir, program);
	logfile = strcpy(malloc(strlen(buf)+1), buf);
}

/*VARARGS*/
logerror(va_alist)
	va_dcl
{
	extern	char *index();
	extern	char *program;
	extern	char logfil[];
	extern	char *sys_errlist[];
	extern	int errno;
	extern	int (*leprfunc)();
	va_list	list;
	long	now;
	char	buf[512];
	char	buf1[512];
	char	*fmt;
	int	logf;
	char	*error;
	char	 *p;

	if (logfile == 0)
		loginit();
	va_start(list);
	fmt = va_arg(list, char *);
	vsprintf(buf, fmt, list);
	if ((p = index(buf, '\n')) != 0)
		*p = 0;
	(void) time(&now);
	error = "log";
	if (errno != 0)
		error = sys_errlist[errno];
	(void) sprintf(buf1, "%s; (%s) %s", buf, error, ctime(&now));
	if ((logf = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
		return;
	(void) write(logf, buf1, strlen(buf1));
	(void) close(logf);
	errno = 0;
	if (leprfunc) {
		(*leprfunc)(
		  "A system error has occured; please notify the deity.\n");
		(*leprfunc)(buf1);
	}
	va_end(list);
}
