#!/usr/bin/perl

use strict;
use warnings;
use POSIX qw(mktime);

my $pmail_log = "$ENV{HOME}/mail/pmail.log";
my $last_check_log = "$ENV{HOME}/.pmail_recent";

my ($cur_date, $new_mail, %folders);

$new_mail = 0;

my $last_check = last_checked();

open PMAIL, $pmail_log or die "Failed to open <$pmail_log> for reading: [$!]";

while (<PMAIL>) {
    chomp();
    
    next unless m/[^\s]/;
    
    if ($new_mail) {
        m#Folder:\s*(\S+)#;
        $folders{$1}++ if $1;
    } else {
        m/^From\s+\S+\s+(.*)/;
        $new_mail++ if to_date($1) > $last_check;
    }
}

close PMAIL;

if ($new_mail) {
    print "You have the following new mail (since " 
        . localtime($last_check) ."):\n";
    print "$_: $folders{$_} messages\n" foreach sort keys %folders;
} else {
    print "You have no new mail\n";
}

open LAST, ">$last_check_log" 
    or die "Failed to open <$last_check_log> for writing: [$!]";
print LAST localtime() . "\n";
close LAST;

exit;

sub last_checked {
    return 0 unless -e $last_check_log;
    open LAST, $last_check_log 
        or die "Failed to open <$last_check_log> for reading: [$!]";
    my $date = <LAST>;
    $date && chomp($date);
    close LAST;
   
    $date ? return to_date($date) : return 0;
}

sub to_date {
    my $date = shift;

    return 0 unless $date;

    my %months;
    @months{qw(jan feb mar apr may jun jul aug sep oct nov dec)} = (0 .. 11);
    
    if (my ($month, $mday, $hour, $min, $sec, $yr) = 
            ($date =~ /\w+\s+(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)/)) {

        return mktime($sec, $min, $hour, $mday, $months{lc($month)}, ($yr - 1900));
    } else {
        return 0;
    }
}
