/*
	pdate - prints date from number of seconds
	Written by D'Arcy J.M. Cain

	Usage:
		pdate [-s|l|u|g] [-f <format string>] [+ [-]<seconds>] [<seconds>]
		-s prints raw seconds (no time zone translation)
		-l display local time (default)
		-u display UTC time
		-g display GMT time (archaic - means same as UTC)
		-f Use format string.  see cftime(3) for details

		A number following '+' is added to whatever the current time
		is.  Note that "+-3600" will subtract an hour.

		A number by itself is treated as the number of seconds since
		the epoch UTC and is used as the current time.

	Examples:
		pdate
			displays current time in default format

		pdate -f "%a, %b %d, %Y"
			displays date only

		pdate +3600
			displays date as of one hour from now

		pdate -f %Y%m%d +-86400
			displays yesterday's date
*/

#include	"cain.h"

#include	<stdio.h>
#include	<stdlib.h>
#include	<time.h>

int
main(int argc, char **argv)
{
	const char	*fmt = "%a %b %d %Y %R";
	char		buf[256];
	time_t		t = time(NULL);		/* default to current time */
	int			local = 1, c;

	initarge(argc, argv);

	while ((c = getarg("slgiuf:h?")) != 0)
	{
		switch (c)
		{
			case 'l': local = 1; break;
			case 'u':
			case 'g': local = 0; break;
			case 'f': fmt = xoptarg; break;
			case 's': printf("%ld\n", (long)(t)); return(0);

			case -1:
				if (*xoptarg == '+')
					t += strtol(xoptarg + 1, NULL, 0);
				else
					t = strtol(xoptarg, NULL, 0);

				break;

			default:		/* note that -h falls into here */
				if (xoptarg)
					fprintf(stderr, "%s\n", xoptarg);

				fprintf(stderr,
							"Usage: %s [-l|g|u] [s] [-f format] [seconds]\n",
							argv[0]);
				fprintf(stderr, "   -l          Local time\n");
				fprintf(stderr, "   -u          UTC time\n");
				fprintf(stderr, "   -g          GMT time (same as UTC)\n");
				fprintf(stderr, "   -f format   cftime type string\n");
				fprintf(stderr, "   -s          print raw seconds\n");
				fprintf(stderr, "   seconds     use instead of current time\n");
				fprintf(stderr, "   +[-]seconds offset current time\n");

				exit(1);
				break;
		}
	}

	if (!t)
	{
		fprintf(stderr, "Invalid time string\n");
		exit(2);
	}

	strftime(buf, sizeof(buf), fmt, local ? localtime(&t) : gmtime(&t));
	puts(buf);
	return(0);
}
