#!/usr/bin/env perl
# source: https://github.com/aspiers/shell-env
use strict;
use warnings;

use Date::Manip qw{Delta_Format DateCalc UnixDate};
use File::Basename;
use File::stat;
use Getopt::Long;

my %opts;
GetOptions(\%opts, 'atime|a', 'ctime|c', 'mtime|m', 'help|h');

my $me = basename $0;

sub usage {
  warn @_, "\n" if @_;
  die <<EOF;
Usage: $me [OPTIONS] FILE AGE
Options:
  -a, --atime
  -c, --ctime
  -m, --mtime (default)

Exit code is zero iff FILE is newer than AGE.

AGE is passed to Date::Manip::ParseDateDelta() to parse;
the following are all valid examples of the same time:

     25hr 2min 58s
     25 hours 3mn -2second
     25 hr 3 minutes -2
     25 hour + 3 min -2 s
     1 day 1 hour 178 s
     90178s
EOF
}

usage() if $opts{help};
usage() unless @ARGV >= 2;

my ($file, @age) = @ARGV;
my $age_str = "@age";
my $st = stat($file);
$st or die "stat($file) failed: $!\n";
my $file_age = $opts{atime} ? $st->atime
             : $opts{ctime} ? $st->ctime
             :                $st->mtime;

my $err;
# Figure out age threshold in seconds since UNIX epoch.
my $threshold = DateCalc("now", "-$age_str", \$err);
die "DateCalc error: $err\n" if $err;

my $threshold2 = UnixDate($threshold, "%s");
#printf "File:     %12s\nThreshold:%12s\n", $file_age, $threshold2;
exit(($file_age > $threshold2) ? 0 : 1);

