
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdarg.h>
#include <proto/dos.h>

#include "lbio_lib.h"
#include "dos_lib.h"
#include "str_lib.h"

#include "cus.h"
#include "defines.h"
#include "rev.h"


void ulog(char *logfile, char *logprog, char *fmtstr, ...)
{
	long t;
	struct tm *tm;
	char logtxt[RANGE_7BIT];
	char logline[RANGE_8BIT];
	FILE *fp = NULL;
	va_list argptr;

	va_start(argptr, fmtstr);
	vsprintf(logtxt, fmtstr, argptr);

	(void)time(&t); /* get timeoffset */
	tm = localtime(&t); /* unpack timeoffset to local time */

	sprintf(logline, "(%02d/%02d-%02d:%02d:%02d) %s,-,- %s\n",
			tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
			logprog, logtxt );

	if (fp = fopen(logfile, "a")) {
		fseek(fp, 0L, SEEK_END);
		fwrite(logline, strlen(logline), 1, fp);
		fclose(fp);
	}

	va_end(argptr);
	return;
}


void giveversioninfo(char *progname)
{
	strupr(progname);
	fprintf(stderr, "%s%s Release %s.%02d (%s) -- receive BSMTP mail%s\n"
					"%s(c) Copyright 1992 Ralf S. Engelschall, All Rights Reserved.\n"
					"%s(c) Copyright 1992 Cyvaned Systems, All Rights Reserved.\n",
					ANSICTL_BOLD_ON, progname, Version, Revision, Date, ANSICTL_NORMAL_DISPLAY,
					progname, progname );
	strlwr(progname);
	return;
}


void giveusage(char *progname)
{
	fprintf(stderr, "Usage: %s <bsmtpfile [-v] [-?]\n", progname);
	return;
}


char *getfield(char *file, char *field, char *target)
{
	FILE *fp = NULL;
	char buffer[RANGE_8BIT];
	char *bufptr;
	char *targetptr;
	char *rc;

	if ((fp = fopen(file, "r")) != NULL) {
		while ((fgets(buffer, RANGE_8BIT, fp)) != NULL) {
			bufptr = buffer;
			if ((strnicmp(bufptr, field, strlen(field))) == 0) {
				bufptr += strlen(field);
				if ((*bufptr == SP) || (*bufptr == HT)) {
					while ((*bufptr == SP) || (*bufptr == HT))
						bufptr++;
					if ((*bufptr != NL) && (*bufptr != NUL)) {
						targetptr = target;
						while ((*bufptr != NL) && (*bufptr != NUL) && (*bufptr != SP) &&
							   (*bufptr != HT) && (*bufptr != '#'))
							*targetptr++ = *bufptr++;
						*targetptr = NUL;
						CU(target);
					}
				}
			}
		}
	}
	rc = NULL;

	CUS:
	if (fp) fclose(fp);
	return rc;
}


char *atime(void)
{
	long t;
	struct tm *tm;
	char caTimezone[10];
	char *cpTimezone;
    char caTmp[40];
    static char *cpaDOW[7] = {	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    static char *cpaMonths[12] = {	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
									"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"	};

	(void)time(&t); /* get timeoffset */
	tm = localtime(&t); /* unpack timeoffset to local time */
	if ((cpTimezone = getfield("uuspool:config", "TimeZone", caTimezone)) == NULL)
		cpTimezone = "GMT";
    sprintf(caTmp, "%s, %d %s %02d %02d:%02d:%02d %s",
				cpaDOW[tm->tm_wday], tm->tm_mday, cpaMonths[tm->tm_mon],
				tm->tm_year % 100, tm->tm_hour, tm->tm_min, tm->tm_sec,
				caTimezone	);
	return(caTmp);
}


