#!/usr/bin/perl -w
# miltercheck, by Kelson Vibber <kelson@speed.net>
# Check for failed milter initializations and restart

use Date::Parse;

$log = '/var/log/maillog';
$stat = '/var/log/miltercheck.last';
$miltercommand = '/etc/init.d/mimedefang restart';
$limit = 10;

# Check last time restarted by this tool
$last = 0;
if (open(IF,"<$stat") ) {
	$last = <IF>;
	close(IF);
}

# Check recent log entries (but only since last restart)
$resets = 0;
open(IX,"/usr/bin/tail -1000 $log |");
while ($line = <IX>) {
	$this = str2time(substr($line,0,15));
	$resets++ if ($this > $last && index($line, 'Milter: initialization failed, temp failing commands') != -1);
}
close(IX);
#print "Found $resets from $last to $this\n";
if ($resets > $limit) {
	print "Found $resets failed initializations; restarting milter\n";
	system ($miltercommand);
	open(OF, ">$stat");
	print OF $this;
	close(OF);
}
