#!/usr/bin/perl -w
#
# This does stuff well
#

use strict;

BEGIN: {

    if ( -f "$ENV{HOME}/.m2procrc" ) {
        do "$ENV{HOME}/.m2procrc";
    }

}

MAIN: {

    my $directory = "$ENV{HOME}/.procmail/m2proc";

    opendir(DIR, $directory);

    my @files = readdir(DIR);

    closedir(DIR);
    open(OFILE, "> $ENV{HOME}/.procmail/m2proc.rc");

    foreach (@files) {
        next if $_ !~ m/\.rule$/;
        # Do things w/ stuff
        # print "$_\n";
        my $file = $_;
        open(TFILE, "< $directory/$file");
        my @a = <TFILE>;
        my $exdate;

        foreach (@a) {
            if ( /Selected expire time is: (forever|\d+)/ ) {
                $exdate = $1;
                last;
            }
        }

        if ( !defined($exdate) ) {
            print(OFILE "# rule from $file is corrupt\n\n");
            close(TFILE);
        } else {
            if ($exdate =~ /\d/) {
                if ($exdate >= time) {
                    print(OFILE @a);
                    close(TFILE);
                    
                } else {
                    close(TFILE);
                    unlink("$directory/$file");
                }
            } else {
                print(OFILE @a);
                close(TFILE);
            }
        }
        
    }

    close(OFILE);

}
