/*
** @(#) Revision 1.1 - 01/17/97
** logwrite.c
**
** ======================================================================= 
** Andrea Whitlock, Mobius Software Services
** whitlock@mobius-soft.com
** 
** Bug reports, questions, and suggestions should be emailed to:
** mobius@mobius-soft.com
**
** This software is provided under the terms of the GNU copyleft
** (ftp://prep.ai.mit.edu/pub/gnu/COPYING-2.0), without a warranty
** of any kind.  Use at your own risk.
** ======================================================================= 
**
** Description:
** Utility functions to write to the message log for logmon.
**
** Notes:
** Set tabstops to 4.
**
*/

#include "logwrite.h"
#include "semutils.h"

static char logwriteSccsId[] = "@(#)logwrite.c	1.1\t01/17/97";
static char logwriteVerId[] = "VER 1.1";

char *
timestamp(void)
{
	time_t 		now;
	struct tm	*nowtime;
	static char	timestr[12];

	/* get current time */
	time(&now);
	nowtime = localtime(&now);

	/* format time */
	sprintf(timestr,"%02d%02d%02d_%02d%02d", nowtime->tm_year, 
		nowtime->tm_mon + 1, nowtime->tm_mday, nowtime->tm_hour, 
		nowtime->tm_min);

	/* return time */
	return timestr;
}

int
logwrite(int semid, char *logfile, char *type, char *message, int nlflag)
{
	struct sembuf	semlock;
	int				semop_ret, retval = 0;
	FILE 			*log;

	/* wait on the semaphore */

	set_sembuf_struct(&semlock, 0, -1, 0);

	while (((semop_ret = semop(semid, &semlock, 1)) == -1) && (errno == EINTR)) 
		;
	if (semop_ret == -1) {
		perror("semaphore decrement failed");
		return 1;
	} 

	/* write to the log file */

	if ((log = fopen(logfile, "a")) != NULL) {
		if (nlflag) 
			fprintf(log, "%s %s %s\n", timestamp(), type, message);
		else
			fprintf(log, "%s %s %s", timestamp(), type, message);
	} else {
		perror("error opening log file");
		retval = 1;
	}
	fclose(log);

	/* release the semaphore */

	set_sembuf_struct(&semlock, 0, 1, 0);

	while(((semop_ret = semop(semid, &semlock, 1)) == -1) && (errno == EINTR))
		;
	if (semop_ret == -1) {
		perror("semaphore increment failed");
	}

	return retval;
}

