#!/usr/bin/perl
#Time-stamp: "2005-08-19 01:27:52 ADT"
#desc{ set file's timestamp to its emacs 'Time-stamp' value }
#
# For each given item, if it's a file, read it for its emacs
# timestamp, and sets its timestamp accordingly, if any emacs
# Time-stamp was found.

require 5 || die;
use strict;
die "Usage: $0 ...filespecs...\n Update the timestamp on given files\n"
    unless @ARGV;

sub DEBUG () {0}

my($buffer, $stamp, $Y,$M,$D, $h,$m,$s, $time, $mtime);
foreach my $x (@ARGV) {
    next unless length $x and -f $x;
    $mtime = (stat(_))[9];
    unless(open(IN, "<$x")) {
	warn "Can't read-open $x: $!\n";
	next;
    }
    read(IN, $buffer, 80*8);
    next unless $buffer =~ m/Time-stamp:[ \t]+\\?["<](.*?)\\?[">]/;
    $stamp = $1;
    use Time::Local; # impute all stamps as being in local TZ
    ($h,$m,$s) = (0,0,0);
    if($stamp =~ s/(\d\d):(\d\d):(\d\d)//) {
	($h,$m,$s) = ($1,$2,$3);
    } else {
	($h,$m,$s) = (0,0,0);
    }

    if($stamp =~ m<^(\d\d\d\d)[-/](\d\d)[-/](\d\d)>) {
	# ISO and ISO-like formats
	($Y,$M,$D) = ($1 - 1900,$2,$3);
    } elsif($stamp =~ m<^(\d\d)[-/](\d\d)[-/](\d\d)>) {
	# yy-mm-dd
	($Y,$M,$D) = ($1,$2,$3);
	$Y += 100 if $Y < 80;
    } else {
	warn "Unknown date format \"$stamp\" in $x\n";
	next;
    }

    if($M < 1 or $M > 12 or $D < 1 or $D > 31) {
	warn "Unknown date format \"$stamp\" in $x\n";
	next;
    }

    DEBUG and print "$x: ($stamp)  ($Y/$M/$D $h:$m:$s)\n";
    $time = timelocal($s,$m,$h,  $D, --$M, $Y);
    if($time == $mtime) {
	DEBUG and print "Skipping useless mod of $x\n";
    } elsif( utime( $time, $time, $x ) ) {
	DEBUG and print localtime($mtime) . " => " . localtime($time), "\n\n";
    } else {
	warn "Couldn't change mtime of $x: $!\n";
    }
}
exit;
__END__
