#!/usr/bin/perl
#
# For each mail message, change its mtime and atime
# to the date of the message
#

use Time::Local;
my @mon = qw(jan feb mar apr may jun jul aug sep oct nov dec);
my %m2n = map {$mon[$_] => $_} (0..11);

if ($ARGV[0] eq '-v') {
  $VERBOSE = shift;
}
for (@ARGV) {
  touch($_);
}

sub touch {
  my $file = shift;
  my $date = get_date($file);
  unless (defined $date) {
    warn "Couldn't locate date field in file '$file'; skipping\n";
    return;
  }

  $date =~ s/\s*(?:sun|mon|tue|wed|thu|fri|sat),?\s+//i;
  my ($da, $mo, $yr, $time, $tz) = split /\s+/, $date;
  unless (exists $m2n{lc $mo}) {
    warn "Couldn't parse date; month was '$mo'; skipping.\n";
    return;
  }
  my ($hour, $min, $sec) = split /:/, $time;
  my $time = timegm($sec, $min, $hour, $da, $m2n{lc $mo}, $yr-1900);

  my ($sign, $tzh, $tzm) = ($tz =~ /([+-]?)(\d\d)(\d\d)/);
  my $tza = ($sign eq "-" ? -1 : 1) * ($tzh * 60 + $tzm) * 60;
  $time -= $tza;

  warn "File $file Date $date Time ", scalar(localtime $time), "\n"
    if $VERBOSE;
  utime $time, $time, $file
    or warn "Couldn't set utimes on file '$file': $!; skipping\n";
}

sub get_date {
  my $file = shift;
  open F, "<", $file or return;
  while (<F>) {
    last unless /\S/;
    if (/^Date:\s+(.*)/) { close F; return $1 }
  }
  close F;
  return;
}
