#!/usr/bin/perl -w
# Recursively scan maildir directories and update the file timestamp
# based on the "Date: " header
#
# Copyright (C) 2004 Emmanuel Lacour <elacour@home-dn.net>
# 
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
# 
# This file is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this file; see the file COPYING.  If not, write to the Free
# Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# 

use strict;
use File::Find;
use Date::Parse qw( str2time );

my $scandir = $ARGV[0];
my $time = time;
my $delivered_time;
my $debug = 0;

if (!$scandir) {
    print "Usage: $0 {dir}\n";
    exit 0;
} elsif (! -d $scandir) {
    print "Couldn't open $scandir: $!\n";
    exit 1;
}

finddepth(\&scan, $scandir);

sub scan {
    # finddepth do chdir before so we need to open the filename without
    # the path ($_), but we report errors with the full file path
    # ($File::Find::name)
    my $file = $_;
    if (-f "$file") {
        if (open (FILE,"$file")) {
            my $date = "";
            while (<FILE>) {
            last if $_ eq "\n";
            if ($_ =~ /^Date: (.*)$/) {
                $date = $1;
                last;
            }
            }
            close FILE;
            if ($date ne "") {
                $delivered_time = str2time("$date");
                print "$File::Find::name : $delivered_time\n" if ($debug);
                utime( $time, $delivered_time, $file);
            } else {
                print STDERR "No date: found for $File::Find::name\n";
            }
        } else {
            print STDERR "Cant't open $File::Find::name: $!\n";
        }
    } else {
        print STDERR "Not a file : $File::Find::name\n" if ($debug);
    }
}

