#!/usr/bin/perl
# (c) 2001 Vlado Keselj <vkeselj@cs.uwaterloo.ca>
#
# Changes every  Last update: Month dd, Year  in a file to proper
# modification time.  Useful for updating .html files, for example.
# The modification time is obtained from the file stat.
#
# Note: A funny thing is that if a change is needed, the program
# itself will change the file modification time, so if the last change
# was yesterday, lastUpdate should be done only once.
#
# Usage:
# lastUpdate file1 file2...    or
# lastUpdate.pl file1 file2...

$Amonth = '(?:January|February|March|April|May|June|July|'.
    'August|September|October|November|December)';

while (@ARGV) {
    $file = shift;

    $mtime = formDate((stat($file))[9]);
    $mode = (stat($file))[2];

    $needs_change = 'no';
    open(I,"<$file") or die "can't open: $file";
    open(O,">$file.bak");
    while (<I>) {
	my $tmp = '';
	while (/(last update: )($Amonth \d\d?, (?:19|20)\d\d)/i) {
	    if ($2 eq $mtime) {
		$tmp .= "$`$&"; $_ = $';
	    } else {
		$tmp .= "$`$1$mtime"; $_ = $';
		$needs_change = 'yes';
	    }
	}
	print O "$tmp$_";
    }
    close(I); close(O);
    if ($needs_change eq 'yes') {
	chmod $mode, "$file.bak";
	rename("$file.bak", $file);
    }
    else { unlink("$file.bak") }
}

sub formDate {
    my $t = shift;
    return ('January','February','March','April','May','June','July',
	    'August','September','October','November','December')
	[(localtime($t))[4]].' '.(localtime($t))[3].', '.
	    (1900+(localtime($t))[5]);
}