/*
 * touchtime.c 
 * BIG BROTHER TOUCHTIME PROGRAM
 * Sean MacGuire - The MacLawran Group Inc.
 * Version 1.4
 * Mar 05th, 2000
 *
 * This program is Copyright (c) 1997-2000
 * The MacLawran Group Inc.
 * All Rights Reserved
 *
 * Create a file with the given name half an hour old...
 * Default creates a file 30 minutes old. (-30)
 * -e returns the current tick
 *
 * Format: touchtime [offset-time] filename
 *	   touchtime -e <offset>
 *	   touchtime -a <offset>
 *	   touchtime -c <timetick>
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <utime.h>

#define NOYEAR 1		/* FOR NOW */
#define debug 	/* printf */

main(argc, argv)
int argc;
char *argv[];
{
	FILE *fp;
        time_t ticks,dateticks;
	struct utimbuf *tb;
	int howlong;
	char *touchfile = (char *)malloc(256);
	char time_asc[32];

	if (argc == 3 && strcmp(argv[1],"-e") && strcmp(argv[1],"-a") && strcmp(argv[1],"-c") ) {	
		sscanf(argv[1], "%d", &howlong);
		sscanf(argv[2], "%s", touchfile);
	}
	else if (argc == 3 && (!strcmp(argv[1],"-e") || !strcmp(argv[1],"-a")) ) {	
		sscanf(argv[2], "%d", &howlong);
	}
	else if (argc == 3 && (!strcmp(argv[1],"-c")) ) {	
		sscanf(argv[2], "%d", &dateticks);
	}
	else if (argc == 2) {
		if ( !strcmp(argv[1],"-e") || !strcmp(argv[1],"-a") ) {
			howlong = 0;
		}
		else {
			howlong = -30;		/* DEFAULT 30 MINUTES AGO */
			sscanf(argv[1], "%s", touchfile);
		}
	}
	else {
		fprintf(stderr, "Format: %s [offset] filename\n", argv[0]);
		exit(1);
	}

	howlong *= 60;			/* NOW IN SECONDS */

        ticks = time(&ticks) + howlong;

	/* Display the date in ASCII based on the time tick given as argument */
	if ( !strcmp(argv[1],"-c") ) {
		sprintf(time_asc,"%s",ctime(&dateticks));
		time_asc[strlen(time_asc)-1] = '\0';
		printf("%s",time_asc);
		exit(0);
	}

	/* Display the time tick value associated */
	if ( !strcmp(argv[1],"-e") ) {
		printf("%d",ticks);
		exit(0);
	}

	/* Display the date in ASCII based on the offset given as argument */
	if ( !strcmp(argv[1],"-a") ) {
		sprintf(time_asc,"%s",ctime(&ticks));
		time_asc[strlen(time_asc)-1] = '\0';
		printf("%s",time_asc);
		exit(0);
	}

	tb=(struct utimbuf *)malloc(sizeof (struct utimbuf));

	tb->actime=ticks;
	tb->modtime=ticks;

	/*
	 * NOW CREATE THE TOUCHFILE
	 * OR JUST CHANGE THE MODIFICATION TIME IF IT ALREADY EXISTS
	 */
	if (fp = fopen(touchfile, "a")){
		fclose(fp);
	}
	else {
		fprintf(stderr, "%s: Can't open filename %s\n", argv[0], touchfile);
		exit(2);
	}
	utime(touchfile, tb);

	exit(0);
}
