/* mtime.c - output a datestamp
 */

#include <stdio.h>
#include <string.h>
#include "getopt.h"
#include "getdate.h"


void display_version(void);


/* Display command-line help for mtime.
 */
void display_help(void)
{
	printf("\
Usage: mtime [DATE]\n\
Output a datestamp for the current time, or for DATE if one is specified.\n\
\n\
      --help            show this help and exit\n\
  -V, --version         show version information and exit\n\
\n\
Report bugs to <mconv@ivarch.com>.\n\
");
}


/* Process command-line arguments and truncate the file given accordingly.
 */
int main(int argc, char *argv[])
{
	struct option long_options[] = {
		{"help", 0, 0, '!'},
		{"version", 0, 0, 'V'},
		{0, 0, 0, 0}
	};
	char *short_options = "V";
	int option_index = 0;
	char buf[1024];
	char *pn;
	time_t t;
	struct tm *tp;
	int c;

	pn = strrchr(argv[0], '/');
	if (pn)
		pn++;
	else
		pn = argv[0];

	do {				    /* read options */
		c = getopt_long(argc, argv, short_options, long_options,
				&option_index);
		if (c < 0)
			continue;
		switch (c) {
		case 'V':
			display_version();
			return (0);
			break;
		case '!':
			display_help();
			return (0);
			break;
		default:
			fprintf(stderr,
				"Try `%s --help' for more information.\n\r",
				pn);
			return (1);
			break;
		}
	} while (c != -1);

	buf[0] = 0;

	while (optind < argc) {
		if (buf[0] != 0)
			strcat(buf, " ");
		strcat(buf, argv[optind]);
		optind++;
	}

	if (buf[0] == 0)
		strcpy(buf, "now");

	t = get_date(buf, 0);
	if (t == -1) {
		printf("Message: 00000000             (Invalid Date)\n");
		fprintf(stderr, "%s: couldn't understand date -- `%s'\n\r",
			pn, buf);
		return (1);
	}

	tp = localtime(&t);
	if (!tp) {
		printf("Message: 00000000             (Invalid Date)\n");
		fprintf(stderr, "%s: couldn't localise date -- `%s'\n\r",
			pn, buf);
		return (1);
	}

	buf[0] = 0;
	strftime(buf, sizeof(buf) - 1, "%a %b %d %H:%M:%S %Y %Z", tp);

	printf("Message: %08lX             (%s)\n", t, buf);

	return (0);
}


/* Shell script version of this program:
 *
 * #!/bin/sh
 * #
 * # Requires the GNU `bc' package (for "dc"), GNU `date', and probably
 * # `bash' and GNU `grep'.
 * #
 * # 22 April 1999 - Andrew Wood <mconv@ivarch.com>
 * 
 * stamp="$*"
 * if test -z "$stamp"; then stamp=`date`; fi
 * 
 * seconds=`date -d "$stamp" +%s`
 * 
 * if echo $seconds | grep -q -- -; then seconds=""; fi
 * 
 * if test -z "$seconds"; then
 *   echo "Message: 00000000             (Invalid Date)"
 *   exit 1
 * fi
 * 
 * hexstamp=`echo 16o${seconds}pq | dc`
 * 
 * while test ${#hexstamp} -lt 8; do hexstamp=0$hexstamp; done
 * 
 * echo -n Message: $hexstamp
 * echo "             ("`date -d "$stamp" "+%a %b %d %H:%M:%S %Y %Z"`")"
 * 
 * # EOF
 */

/* EOF */
