#!/usr/bin/perl -w
#
# $Revision: 1.4 $ $Date: 2012-07-26 17:11:48-04 $
# $Source: /home/vogelke/bin/RCS/mtrecent,v $
# $Host: sys7.com $
# $UUID: d4766394-ffbd-3350-94b8-2b8221f0e230 $
#
#<mtrecent: set directory modtime to that of its most recent file.
#           prints modtime and directory name.

use strict;
use Cwd;

my $cwd = getcwd();

# Find the most recent modtime, excluding current/parent directories.
foreach my $dir (@ARGV) {
    unless (-d $dir) {
        warn "$dir: not a directory";
        next;
    }

    chdir($dir) or die "chdir $dir: $!";
    opendir(my $dh, ".") or die "opendir $dir: $!\n";

    my ($max, $mtime) = (0, 0);
    while (defined($_ = readdir($dh))) {
        next if ($_ eq '.' || $_ eq '..');
        $mtime = (stat($_))[9];

        if (defined($mtime)) {
            #print "$mtime $_\n";
            $max = $mtime if $mtime > $max;
        } else {
            warn "stat failed: $dir/$_";
        }
    }

    closedir($dh);
    utime($max, $max, '.') or warn "$dir: unable to set modtime $max";

    print "$max $dir\n";
    chdir($cwd) or die "unable to return to $cwd: $!";
}

exit(0);
