#!/usr/bin/perl

use strict;
use Date::Format;
use Date::Parse;
use File::Find;

my @files;

if ( -d '/usr/home/wilmesj/public_html/fiat/posts') {
    chdir('/usr/home/wilmesj/public_html/fiat/posts');
} else {
    chdir('/home/josh/public_html/fiat/posts');
}    

File::Find::find({wanted => sub {
    /^.*txt\z/s && push @files, $File::Find::name;
}}, '.');

foreach my $file (@files) {
    open(F, "<$file") || die "Can't read $file: $!\n";
    my $title = <F>;
    close(F);
    
    my ($postdate) = ($title =~ /^(\d+\/\d+\/\d+):/);
    if (! defined($postdate)) {
        warn("No date in title to $file") 
	  unless ($file =~ /\/(welcome|info)\//);
	next;
    }
    
    my $mtime = (stat($file))[9];
    my $mtimestr = time2str('%m/%d/%Y', $mtime);
      
    if (! (date_eq($postdate, $mtimestr))) {
        print "$file has an improper mtime ($mtimestr, not $postdate) - fixing.\n";
	fix_mtime($file, $postdate);
    }
}    

    
sub date_eq {
    my ($datea, $dateb) = @_;
    
    my ($m, $d, $y) = split '/', $datea;
    if ($y < 100) { $y += 2000; }
    $datea = sprintf("%d/%d/%d", $m, $d, $y);
    
    ($m, $d, $y) = split '/', $dateb;
    if ($y < 100) { $y += 2000; }    
    $dateb = sprintf("%d/%d/%d", $m, $d, $y);
    
    return ($datea eq $dateb);
}

sub fix_mtime {
    my ($file, $date) = @_;
    
    my $new_mtime = str2time($date);
    utime(time, $new_mtime, $file);    
}
