/* $Id: newer.c,v 1.8 2005/04/05 17:49:18 taco Exp $
   Public domain.  */

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

int i;
int verbose=0;
int missing_infile=0;

/*
 *      newer src1 [ src2 ... srcN ] dependent
 *
 *      returns 0 if files `src1' ... `srcN' exist and 
 *      at least one of them is not older than `dependent'
 *      or if `dependent' doesn't exist.
 */

int
main (int argc, char **argv) {
	struct stat x, y;
	/* We assume that newer is called with at most one optional
	 * argument.  Checking for --verbose first handles cases like
	 *     newer --verbose --help 
	 * gracefully.
	 */

	if ( argc > 1 && ( strcmp (argv[1], "-v") == 0 ||
			   strcmp (argv[1], "-verbose") == 0 ||
			   strcmp (argv[1], "--verbose") == 0)) {
	  verbose=1;
	  argv+=1;
	  argc-=1;
	}

	if (argc > 1 && (strcmp (argv[1], "--help") == 0
                         || strcmp (argv[1], "-help") == 0)) {
          fputs ("Usage: newer [OPTION] src1 [ src2 ... srcN ] dependent\n\
  Exit successfully if `src1' ... `srcN' exist and at least\n\
  one of them is not older than `dependent'.\n\
  Also exit successfully if `dependent' doesn't exist.\n\
\n\
--help      display this help and exit\n\
--verbose   list missing input files\n\
--version   output version information and exit\n\n", stdout);
	  fputs ("Email bug reports to metapost@tug.org.\n", stdout);
	  exit(0);
	} else if (argc > 1 && (strcmp (argv[1], "--version") == 0
                                || strcmp (argv[1], "-version") == 0)) {
	  fputs ("newer 0.893\n\
This program is in the public domain.\n\
Primary author of newer: John Hobby.\n", stdout);
	  exit (0);
	}
	
	/* do we have at leat two arguments? */
	if (argc < 3) {
	  fputs ("newer: Too few arguments. \
Try `newer --help' for more information.\n",stderr);
	  exit (1);
	}

	/* do all the input files exist?
	   --verbose option lists missing input files */
 	for (i=1; i<(argc-1); i++) {
 	  if (stat (argv[i], &x) < 0) {
	    if (verbose)
	      fprintf (stderr, "newer: file `%s' doesn't exist.\n", 
		       argv[i]);
	    missing_infile=1;
	  }
	}
	if (missing_infile)
	  exit (1);

        /* does the output file exist? */
        if (stat (argv[argc-1], &y) < 0) { /* file doesn't exist */
	  exit(0);
         }

        /* succeed unless one of the the input file is older than
	   the output file or both files have the same timestamp */
 	for (i=1; i<(argc-1); i++) {
 	  stat (argv[i], &x);
	  if (x.st_mtime >= y.st_mtime)
		exit(0);
        }

        /* otherwise, fail */
        exit(1);	
}
