#!@@PERL@@ -w
# -*- perl -*-

=head1 NAME

postfix_mailvolume - Plugin to monitor the volume of mails delivered
  by postfix.

=head1 APPLICABLE SYSTEMS

Any postfix.

=head1 CONFIGURATION

The following shows the default configuration.

  [postfix*]
    env.logdir /var/log
    env.logfile syslog

=head1 INTERPRETATION

The plugin shows the number of bytes of mail that has passed through
the postfix installation.

=head1 MAGIC MARKERS

  #%# family=auto
  #%# capabilities=autoconf

=head1 BUGS

None known

=head1 VERSION

 $Id$

=head1 AUTHOR

Copyright (C) 2002-2008.

No author is documented.

=head1 LICENSE

GPLv2

=cut

use strict;
use Munin::Plugin;

my $pos   = undef;
my $volume = 0;
my $LOGDIR  = $ENV{'logdir'}  || '/var/log';
my $LOGFILE = $ENV{'logfile'} || 'syslog';

sub parseLogfile {
    my ($fname, $start) = @_;

    my ($LOGFILE,$rotated) = tail_open($fname,$start);

    my $line;

    while ($line =<$LOGFILE>) {
	chomp ($line);

	if ($line =~ /qmgr.*from=.*size=([0-9]+)/) {
	    $volume += $1;
	}
    }
    return tail_close($LOGFILE);
}

if ( $ARGV[0] and $ARGV[0] eq "autoconf" ) {
    my $logfile;
    `which postconf >/dev/null 2>/dev/null`;
    if (!$?) {
	$logfile = "$LOGDIR/$LOGFILE";

	if (-f $logfile) {
            if (-r "$logfile") {
                print "yes\n";
                exit 0;
            } else {
                print "no (logfile '$logfile' not readable)\n";
            }
	} else {
	    print "no (logfile '$logfile' not found)\n";
	}
    } else {
	print "no (postfix not found)\n";
    }

    exit 0;
}


if ( $ARGV[0] and $ARGV[0] eq "config" ) {
    print "graph_title Postfix bytes throughput\n";
    print "graph_args --base 1000 -l 0\n";
    print "graph_vlabel bytes / \${graph_period}\n";
    print "graph_scale yes\n";
    print "graph_category postfix\n";
    print "volume.label throughput\n";
    print "volume.type DERIVE\n";
    print "volume.min 0\n";
    exit 0;
}


my $logfile = "$LOGDIR/$LOGFILE";

if (! -f $logfile) {
    print "volume.value U\n";
    exit 1;
}

($pos,$volume) = restore_state();

if (!defined($volume)) {
    
    # No state file present.  Avoid startup spike: Do not read log
    # file up to now, but remember how large it is now, and next
    # time read from there.

    $pos = (stat $logfile)[7]; # File size

    $volume = 0;
} else {
    $pos = parseLogfile ($logfile, $pos);
}

print "volume.value $volume\n";

save_state($pos,$volume);

# vim:syntax=perl
