#=======================================
# rm old mail v0.1.0
#=======================================
# Copyright (c) 2001 Tobias von Koch <tvk@von-koch.com>
#
# All rights reserved. Redistribution and use in source and binary
# forms, with or without modification, are permitted provided that
# this copyright notice is retained.
#
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR
# CONSEQUENTIAL DAMAGES RESULTING FROM THE USE OR MISUSE OF THIS
# SOFTWARE.
#
########################################
# Config
########################################
# $tempdir
# A tmp directory the script is allowed to write to.
# If you have some untrusted users which have shells on your host,
# _never_ use /tmp for security reasons. Create a directory which is only
# writable by the uid this script is running under (e.g. root).

my $tempdir = "/tmp";

# $max_age
# The maximum age (in months) a message may reach
#

my $max_age = 6;

########################################
########################################

use Fcntl ':flock';
use Date::Calc qw( Parse_Date Delta_Days Today );
use strict;

sub Is_Too_Old ($);

my $tempfile = "$tempdir/mbox$$";

if (!defined($ARGV[0])) { die("No mbox specified.\n"); }
if (!-e $ARGV[0]) { exit(); }

while (-e $tempfile) { $tempfile .= "_"; }
system("cp -p $ARGV[0] $tempfile");

open (TMP, ">$tempfile") || die("Unable to open temporary file $tempfile: $!\n");
open (MBOX, "<$ARGV[0]") || die("Unable to open mbox $ARGV[0]: $!\n");

flock(MBOX,LOCK_EX);

my ($line, $drop);

while ($line = <MBOX>) {
	if ($line =~ /^From (\S+) +(.+)/) {
		my ($from,$date) = ($1,$2);

		if ($from ne "MAILER-DAEMON" && Is_Too_Old($date)) {
			$drop = 1;
			next;
		}

		$drop = 0;
	}

	if (!$drop) { print TMP $line; }
}

close (TMP) || die ("Unable to close temporary file $tempfile: $!\n");

rename($tempfile, $ARGV[0]) || die ("Unable to move $tempfile to $ARGV[0]: $!\n");

flock(MBOX,LOCK_UN);
close (MBOX);

##########################################

sub Is_Too_Old($) {
	my ($year,$month,$day) = Parse_Date($_[0]);
	my ($nowyear, $nowmonth, $nowday) = Today();
	my ($age);

	$age = Delta_Days($year,$month,$day,
                          $nowyear,$nowmonth,$nowday);

	if ($age/30 > $max_age) {
		return 1;
	}

	return 0;
}

