/*
 *	Copyright 1990 by Rayan S. Zachariassen, all rights reserved.
 *	This will be free software, but only when it is finished.
 */

#include "hostenv.h"
#include "mailer.h"

static char *weekday[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

char *monthname[] = {	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
			"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

char *
rfc822tz(ts, prettyname)
	struct tm *ts;
	int prettyname;
{
	char *cp;
	static char zone[18];
	int sign, offset;

#ifdef	USE_BSDTIMEZONE
	struct timezone tz;
	struct timeval tv;
	extern char *timezone();

	gettimeofday(&tv, &tz);	/* this can't fail, right?? */
	offset = tz.tz_minuteswest - (ts->tm_isdst ? 60 : 0);
	sign = offset >= 0;
	if (!sign)
	  offset = -offset;
	sprintf(zone, "%c%02d%02d",
		sign ? '-' : '+', offset / 60, offset % 60);
	cp = zone;
	if (prettyname)
	  sprintf(cp+5," (%s)",ts->tm_zone);


#else	/* !USE_BSDTIMEZONE */
#ifdef	USE_SYSVTIMEZONE
	/* daylight, timezone, altzone, declared in <time.h> */

#if	!defined(_HPUX_SOURCE) && !defined(_POSIX_SOURCE)
	if (daylight && ts->tm_isdst)
	  offset = altzone;
	else
#endif
	  offset = timezone;
	sign = offset >= 0;
	if (!sign)
	  offset = -offset;
	sprintf(zone, "%c%02d%02d", sign ? '-' : '+',
		offset / (60*60), (offset % (60*60)) / 60);
	cp = zone;

	if (prettyname)
	  strcat(zone+5, tzname[0 != daylight]);

#else	/* !USE_SYSVTIMEZONE */
#if 0
	cp = tzname[ts->tm_isdst];	/* this doesn't always work */
#else
	offset = ts->tm_gmtoff;
	sign = offset >= 0;
	if (!sign)
		offset = -offset;
	sprintf(zone, "%c%02d%02d", sign ? '+' : '-',
		offset / (60*60), (offset % (60*60)) / 60);
	if (prettyname)
		sprintf(zone+5," (%s)",ts->tm_zone);
	cp = zone;
#endif
#endif	/* USE_SYSVTIMEZONE */
#endif	/* USE_BSDTIMEZONE */
	return cp;
}

/* Like ctime(), except returns RFC822 format (variable length!) date string */

u_char *
rfc822date(unixtimep)
	long *unixtimep;
{
	static u_char buf[40];
	struct tm *ts;

	ts = localtime(unixtimep);
	sprintf((char *)buf, "%s, %d %s %d %02d:%02d:%02d %s\n",
		weekday[ts->tm_wday], ts->tm_mday, monthname[ts->tm_mon],
		1900+ts->tm_year, ts->tm_hour, ts->tm_min, ts->tm_sec,
		rfc822tz(ts, 0));
	return buf;
}
