#!/usr/bin/perl -w
#
# $Revision: 1.3 $ $Date: 2012-07-26 17:11:48-04 $
# $Source: /home/vogelke/bin/RCS/mlage,v $
# $Host: sys7.com $
# $UUID: 25346d58-9502-3eba-8105-dd48bec601b9 $
#
#<mlage: most likely age
#
# Read a given directory, set the most likely modtime of the
# directory by finding the median file modification time.
#
# Don't assume the current directory, too easy to make a mistake by
# simply leaving off an argument.

use strict;
use File::Basename;
use Cwd;

use subs qw/median modtime numeric/;
my ($dir, $med, $t, @times);

my $myname = basename($0);
$myname =~ s/\.\w*$//;    # strip any extension

# Read one or more directories, ignoring junk.

my $cwd = getcwd;

foreach $dir (@ARGV) {
    $dir =~ s!/$!!;

    unless (-d $dir) {
        warn "$dir: not a directory\n";
        next;
    }

    chdir($dir) or die "$dir: unable to chdir: $!\n";
    opendir(my $dh, ".") or die "can't read ., how did you get here?\n";

    @times = ();
    foreach my $file (readdir($dh)) {
        next unless -f $file;
        next if $file =~ /^($myname|index.htm)$/;
        $t = modtime($file);
        push(@times, $t) if defined($t);
    }

    closedir($dh);
    $med = median(\@times);
    utime($med, $med, ".") or die "utime: $!\n";
    print scalar localtime($med), ": $dir\n";

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

exit(0);

sub numeric { $a <=> $b; }

sub modtime { my $path = shift; return (stat($path))[9]; }

sub median {
    @_ == 1 or die('Sub usage: $median = median(\@array);');
    my ($array_ref) = @_;
    my $count = scalar @$array_ref;

    # Sort a COPY of the array, leaving the original untouched
    my @array = sort numeric @$array_ref;
    if ($count % 2) {
        return $array[int($count / 2)];
    }
    else {
        return ($array[$count / 2] + $array[$count / 2 - 1]) / 2;
    }
}
