#!/usr/bin/perl -w

# this script can be run periodicly on log mail.log file to report
# change since last run.
#
# Dobrica Pavlinusic <dpavlin@rot13.org>
# http://www.rot13.org/~dpavlin/sysadm.html
#
# Usage: parse_maillog.pl /path/to/mail.log [count_regex,count_regex,...]
#
# Results for optional count regexps will be dumped to stdout after data
# for number of internal mails, size of internal mails, number of
# external mails and size of external mails
#
# So, if you want also to count number of pop and imap accesses from your
# mail.log you can use:
#
#	parse_maillog.pl /var/log/mail.log popd,imapd
#
# and modify your target file accordingly

use strict;

my $log="/var/log/mail.log";

# edit this to your configuration!

my $domain='@pliva.hr';
my $delta="/var/tmp/";

my $debug=0;
my $skip_delta=0;

$log = shift @ARGV if ($ARGV[0] && -r $ARGV[0]);

# take patterns to count (separated by ,)
my @count_patt = split(/,/,shift @ARGV) if (@ARGV);
my %count;

# counters
my ($mail_int, $mail_ext) = (0,0,0,0);
# size
my ($size_int, $size_ext) = (0,0,0,0);

open(LOG,$log) || die "can't open log '$log': $!";

my $tmp_log=$log;
$tmp_log=~s/\W/_/g;
$delta.=$tmp_log.".offset";

if (-e $delta) {
	open(D,$delta) || die "can't open delta file '$delta' for log '$log': $!";
	my $offset=<D>;
	chomp $offset;
	close(D);
	my $log_size = -s $log;
	print STDERR "log size: $log_size\n" if ($debug);
	if ($offset <= $log_size) {
		seek(LOG,$offset,0);
		print STDERR "skipping to position: $offset\n" if ($debug);
	} else {
		print STDERR "reset position to begin\n" if ($debug);
	}
}

my $lines=0;

while(<LOG>) {
	chomp;
	if (m/from=[^\@]+\@[^\@]+$domain[>,]+\s+.*size=(\d+)/ || m/from=[^\@]+[,\s]+.*size=(\d+)/ ) {
		$mail_int++;
		$size_int+=$1;
	} elsif (m/from=.*size=(\d+)/) {
		$mail_ext++;
		$size_ext+=$1;
	}
	foreach my $patt (@count_patt) {
		if (m/$patt/i) {
			$count{$patt}++;
		}
	}
	$lines++;
}

print STDERR "processed $lines lines...\n" if ($debug);

if (! $skip_delta) {
	open(D,"> $delta") || die "can't open delta file '$delta' for log '$log': $!";
	print D tell(LOG);
	close(D);
} else {
	print STDERR "new delta not written to file!\n";
}

print STDERR "last position in log: ".tell(LOG)."\n" if ($debug);

print "$mail_int\n$size_int\n$mail_ext\n$size_ext\n";

foreach my $patt (@count_patt) {
	print $count{$patt} || 0,"\n";
}
