#!/usr/bin/perl

=head1 NAME

spamstats - Plugin to graph spamassassin throughput

=head1 CONFIGURATION

This plugin does not have any configuration

=head1 AUTHOR

Unknown author

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=contrib
 #%# capabilities=autoconf

=cut

use strict;

use Munin::Plugin;

my $logfile = (defined $ENV{logdir} ? $ENV{logdir} : "/var/log/");
$logfile .= $ENV{logfile} || "syslog";

my $rotlogfile;

if (-f "$logfile.0")
{
    $rotlogfile = $logfile . ".0";
}
elsif (-f "$logfile.1")
{
    $rotlogfile = $logfile . ".1";
}
elsif (-f "$logfile.01")
{
    $rotlogfile = $logfile . ".01";
}
else
{
    $rotlogfile = $logfile . ".0";
}

if ( $ARGV[0] and $ARGV[0] eq "config" )
{
    print "host_name $ENV{FQDN}\n";
    print "graph_title SpamAssassin throughput\n";
    print "graph_args --base 1000 -l 0\n";
    print "graph_vlabel mails/\${graph_period}\n";
    print("graph_category spamfilter\n");
    print "graph_order ham spam\n";
    print "ham.label ham\n";
    print "ham.type DERIVE\n";
    print "ham.min 0\n";
    print "ham.draw AREA\n";
    print "spam.label spam\n";
    print "spam.type DERIVE\n";
    print "spam.min 0\n";
    print "spam.draw STACK\n";
    exit 0;
}
elsif ( defined($ARGV[0]) and $ARGV[0] eq "autoconf" )
{
    open(my $log, '<', $logfile) or ( print("no (Could not open $logfile)\n") and exit );
    while(<$log>)
    {
        if( /clean message/ or /dentified spam/ )
        {
            print "yes\n";
            close($log);
            exit;
        }
    }
    print "no (No spamassasin messages found)\n";
    close($log);
    exit;
}

if (! -f $logfile and ! -f $rotlogfile)
{
    print "ham.value U\n";
    print "spam.value U\n";
    exit 0;
}

my ($pos, $ham, $spam) = restore_state();

$ham = 0 unless defined($ham);
$spam = 0 unless defined($spam);

my $startsize = (stat $logfile)[7];

if (!defined $pos)
{
    # Initial run.
    $pos = $startsize;
}

if ($startsize < $pos)
{
    # Log rotated
    if (-f $rotlogfile) {
        parselogfile ($rotlogfile, $pos, (stat $rotlogfile)[7]);
    }
    $pos = 0;
}

$pos = parselogfile ($logfile, $pos, $startsize);

$pos = $startsize;

print "ham.value $ham\n";
print "spam.value $spam\n";

save_state($pos, $ham, $spam);

sub parselogfile
{
    my ($fname, $start, $stop) = @_;
	my ($logfd, $reset) = tail_open($fname, $start);

    while (tell($logfd) < $stop)
    {
	my $line =<$logfd>;
	chomp ($line);

	if ($line =~ m/clean message/)
	{
	    $ham++;
	}
	elsif ($line =~ m/identified spam/)
	{
	    $spam++;
	}
    }
    return tail_close($logfd);
}
