#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/common/log.c,v 2.3 1995/10/11 02:56:04 empire 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>
#ifdef Rel4
#include <string.h>
#include <time.h>
#endif /* Rel4 */
#include "deity.h"
#include "player.h"

static	s_char *logfile;

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

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

/*VARARGS*/
void logerror(va_alist)
	va_dcl
{
	extern	s_char logfil[];
#ifndef Rel4
	extern	s_char *sys_errlist[];
#endif 
#ifndef sgi
	extern	int errno;
#endif /* sgi */
	va_list	list;
#if defined Rel4
	time_t	now;
#else /* Rel4 */
	long	now;
#endif /* Rel4 */
	s_char	buf[512];
	s_char	cbuf[512];
	s_char	buf1[512];
	s_char	*format;
	int	logf;
/*	s_char	*error; */
	s_char	 *p;

	if (logfile == 0)
		loginit();
	va_start(list);
	format = va_arg(list, s_char *);
	vsprintf(buf, format, 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));
*/
	strcpy(cbuf, ctime(&now));
	if ((p = index(cbuf, '\n')) != 0)
		*p = 0;
	(void) sprintf(buf1, "%s %s\n", cbuf, buf);
	if ((logf = open(logfile, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
		return;
	(void) write(logf, buf1, strlen(buf1));
	(void) close(logf);
	errno = 0;
#ifdef notdef
	if (player) {
		pr("A system error has occured; please notify the deity.\n");
		pr(buf1);
	}
#endif
	va_end(list);
}

/*VARARGS*/
void filelogerror(va_alist)
	va_dcl
{
	extern	s_char program[];
	extern	s_char logfil[];
#ifndef Rel4
	extern	s_char *sys_errlist[];
#endif /* Rel4 */
#ifndef sgi
	extern	int errno;
#endif /* sgi */
	va_list	list;
	long	now;
	s_char	buf[512];
	s_char	buf1[512];
	s_char	*format;
	int	logf;
	s_char	*error;
	s_char	 *p;

	if (logfile == 0)
		loginit();
	va_start(list);
	format = va_arg(list, s_char *);
	vsprintf(buf, format, list);
	if ((p = index(buf, '\n')) != 0)
		*p = 0;
	(void) time(&now);
	error = "log";
	if (errno != 0)
#ifdef Rel4
		error = strerror (errno);
#else
		error = sys_errlist[errno];
#endif /* Rel4 */
	(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;
	va_end(list);
}
