#!/usr/bin/perl -w
use warnings;
use strict;

use Getopt::Long;
use File::Find ();

my $maildir   = undef;
my $keep_days = 14;
my $dry_run   = 0;
my $quiet     = 0;

my $options_okay = GetOptions(
    'keep=i'       => \$keep_days,
    'usage|help|?' => \&usage,
    'dry-run'      => \$dry_run,
    'quiet'        => \$quiet,
);

# we accept exactly one non-option argument, that is the maildir
usage() unless ( $options_okay && ( $#ARGV == 0 ) );
$maildir = $ARGV[0];

# quiet debugging kinda beats the point
if ($dry_run) { $quiet = 0 }

my $count = 0;

# Traverse desired filesystems
File::Find::find( { wanted => \&wanted }, $maildir );
print "$count files " . ($dry_run ? "found" : "deleted") . "\n" unless ( $quiet );

### end of main program, start of utility subs ###

sub wanted {
    my ( $dev, $ino, $mode, $nlink, $uid, $gid );

    return unless ( ( $dev, $ino, $mode, $nlink, $uid, $gid ) = lstat($_) );

    if ( -f _ && ( int( -M _ ) > $keep_days ) ) {
        unlink($_) unless $dry_run;
        $count++;
    }
}

sub usage {
    print "    Usage: \n";
    print "         $0 /path/to/maildir [--keep days] [--dry-run] [--quiet]\n";
    exit 1;
}