[net.sources] utime - command level equivalent of utime

barryg@sdcrdcf.UUCP (09/20/83)

#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#define min(uix,uiy)    (uix<uiy?uix:uiy)
/*
 *         utime [-] file1 [file2]
 *
 * causes file1 to have the same 'accessed' and 'updated' times as file2.
 * If file2 is omitted, utime will use the "oldest" of:
 *  ,file1
 *  file1.bak
 *  file1.BAK
 *  file1.~
 *  .deleted/file1
 *  .deleted/any-of-the-above
 * E.g. utime xxx.h ,xxx.h causes the current version of xxx.h to have the
 * same 'updated' time as the previous version.  Useful for fooling make.
 * As usual, an initial '-' allows file1 to begin with a hyphen without
 * getting confused with a flag argument.
 *
 */

time_t  origt;

usage()
       {printf("Usage -- utime ");
	printf(               "[-] file1 file2\n");
	printf("or       utime [-] file1\n");
	exit(1);
       }

main(argc, argv)
    int    argc;
    char **argv;
       {char           *a, *fn1, *fn2 = NULL, *d = NULL;
	time_t          timep[2];
	struct stat     sbuf;
	int             s, i;

	argc--;
	if (argc < 1)
		usage();
	i = 1;
	a = argv[i];
	if (a[0] == '-')
		if (a[1] == '\0')
			i = 2;
		else usage();

	fn1 = argv[i];
	if (argc == ++i)
	      fn2 = argv[i];
	else if (argc > i)
	      usage();

	s = stat(fn1, &sbuf);
	if (s < 0)
	     {printf("cannot stat: %s\n", fn1);  exit(2);}
	timep[0] = sbuf.st_atime;
	origt = sbuf.st_mtime;
	if (fn2 != NULL)
		timep[1] = getmtime(fn2, -1);
	else timep[1] = getoldest(fn1);

	utime(fn1, timep);
	return 0;
       }

getmtime(fn, prev)
    char *fn;
    int prev;
       {int             s;
	struct stat     sb;

	s = stat(fn, &sb);
	if (s == 0)
		return sb.st_mtime;
	else if (prev == -1)
	       {printf("cannot stat: %s\n", fn);  exit(3);}
	else return prev;
       }

getoldest(fn)
    char *fn;
       {char    buf[256];
	int     l;
	time_t  t1, t2;

	t1 = origt;
	sprintf(buf, "%s.~", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	sprintf(buf, "%s.bak", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	sprintf(buf, "%s.BAK", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	sprintf(buf, ",%s", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	if (chdir(".deleted") < 0)
		return t1;
	t2 = getmtime(fn, t1);
	t1 = min(t1, t2);
	sprintf(buf, "%s.~", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	sprintf(buf, "%s.bak", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	sprintf(buf, "%s.BAK", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	sprintf(buf, ",%s", fn);
	t2 = getmtime(buf, t1);
	t1 = min(t1, t2);
	chdir("..");
	return t1;
       }