/* UNTOUCH! */

#include <sys/param.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/file.h>
#include <errno.h>
#include <syslog.h>
#include <utmp.h>

struct	timeval tv;
struct	timezone tz;
char	*ap, *ep, *sp;
int	uflag;

static	int dmsize[12] =
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static	char *usage = "usage: untouch file [-u] [yymmddhhmm[.ss]]\n";

char	*strcpy(), *strncpy();

main(argc, argv)
	int argc;
	char *argv[];
{
	char filename[256];
	struct timeval newtime[2];

	(void) gettimeofday(&tv, &tz);

	if (argc > 1 && argv[1][0] != '-') {
		strcpy(filename,argv[1]);
		argc--;
		argv++;
	} 
	else {
		fprintf(stderr,usage);
		exit(1);
	} 

	while (argc > 1 && argv[1][0] == '-') {
		while (*++argv[1])
		    switch ((int)argv[1][0]) {

		    case 'u':
			uflag++;
			break;

		    default:
			fprintf(stderr, usage);
			exit(1);
		}
		argc--;
		argv++;
	}

	grab(argv[1]);
	newtime[0] = tv;
	
	if (argc > 2) {
		grab(argv[2]);
		newtime[1] = tv;
	} 
	else
		newtime[1] = newtime[0];
	
	utimes(filename,newtime);
	exit(0);
}

long grab(foo)
char *foo;
{
	ap = foo;

	if (gtime()) {
		fprintf(stderr, usage);
		exit(1);
	}
	/* convert to GMT assuming local time */
	if (uflag == 0) {
		tv.tv_sec += (long)tz.tz_minuteswest*60;
		/* now fix up local daylight time */
		if (localtime((time_t *)&tv.tv_sec)->tm_isdst)
			tv.tv_sec -= 60*60;
	}
} 
gtime()
{
	register int i, year, month;
	int day, hour, mins, secs;
	struct tm *L;
	char x;

	ep = ap;
	while(*ep) ep++;
	sp = ap;
	while(sp < ep) {
		x = *sp;
		*sp++ = *--ep;
		*ep = x;
	}
	sp = ap;
	(void) gettimeofday(&tv, (struct timezone *)0);
	L = localtime((time_t *)&tv.tv_sec);
	secs = gp(-1);
	if (*sp != '.') {
		mins = secs;
		secs = 0;
	} else {
		sp++;
		mins = gp(-1);
	}
	hour = gp(-1);
	day = gp(L->tm_mday);
	month = gp(L->tm_mon+1);
	year = gp(L->tm_year);
	if (*sp)
		return (1);
	if (month < 1 || month > 12 ||
	    day < 1 || day > 31 ||
	    mins < 0 || mins > 59 ||
	    secs < 0 || secs > 59)
		return (1);
	if (hour == 24) {
		hour = 0;
		day++;
	}
	if (hour < 0 || hour > 23)
		return (1);
	tv.tv_sec = 0;
	year += 1900;
	for (i = 1970; i < year; i++)
		tv.tv_sec += dysize(i);
	/* Leap year */
	if (dysize(year) == 366 && month >= 3)
		tv.tv_sec++;
	while (--month)
		tv.tv_sec += dmsize[month-1];
	tv.tv_sec += day-1;
	tv.tv_sec = 24*tv.tv_sec + hour;
	tv.tv_sec = 60*tv.tv_sec + mins;
	tv.tv_sec = 60*tv.tv_sec + secs;
	return (0);
}

gp(dfault)
{
	register int c, d;

	if (*sp == 0)
		return (dfault);
	c = (*sp++) - '0';
	d = (*sp ? (*sp++) - '0' : 0);
	if (c < 0 || c > 9 || d < 0 || d > 9)
		return (-1);
	return (c+10*d);
}
