#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<utime.h>

/** Copy the timestamp of a file to another
 * @param name	the file name whose timestamp is to be rewritten
 * @param diff	difference from current timestamp
 * @return	zero if successful
 */
static int
touch_file (const char* name,
	    time_t diff)
{
  int status;
  struct stat statbuf;
  if ((status = stat (name, &statbuf))) {
    (void) fputs (name, stderr);
    perror (": stat");
  }
  else {
    struct utimbuf utim;
    utim.actime = utim.modtime = statbuf.st_mtime + diff;
    if ((status = utime (name, &utim))) {
      (void) fputs (name, stderr);
      perror (": utime");
    }
  }
  return status;
}

/** Main program
 * @param argc	argument count
 * @param argv	argument vector
 * @return	zero on success
 */
int
main (int argc, char** argv)
{
  int i;
  time_t diff;
  char* end;
  if (argc < 2) {
    fputs ("usage: toucher diff_in_seconds file...\n", stderr);
    return 1;
  }
  diff = strtol (argv[1], &end, 0);
  if (!*argv[1] || *end) {
    fputs ("invalid time offset: ", stderr);
    fputs (argv[1], stderr);
    putc ('\n', stderr);
    return 1;
  }
  for (i = 2; i < argc; i++)
    if (touch_file (argv[i], diff))
      return 2;
  return 0;
}

