#!/usr/bin/env perl
# -*- perl -*-

=head1 NAME

pgld - Plugin to monitor Peer Guardian Linux blockrates

=head1 CONFIGURATION

 [pgld]
   env.pgldlog /var/log/pgl/pgld.log

=head1 LICENSE

GPLv2

=head1 AUTHOR

Daniel Lee <Longinus00@gmail.com>

=head1 MAGICK MARKERS

  #%# family=network
  #%# capabilities=autoconf

=cut

use strict;
use warnings;
use Munin::Plugin;

my $LOG = $ENV{'pgldlog'} || '/var/log/pgl/pgld.log';

sub trim {
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

sub autoconf {
    if(-r $LOG) {
        print "yes\n";
    }
}

sub config {
    print << "EOF";
graph_title Peer Guardian hits
graph_info This graph shows the number of connections blocked per minute
graph_args --base 1000 -l 0
graph_vlabel hits per minute
graph_category network
graph_period minute
hits.label hits
hits.type DERIVE
hits.min 0
EOF
}

if($ARGV[0] and $ARGV[0] eq "autoconf") {
    autoconf
}
elsif($ARGV[0] and $ARGV[0] eq "config") {
    config
}
else {
    my $IP4 = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
    my %positions = restore_state();

    if(! -r $LOG) {
        print "can't open $LOG for reading.\n";
    }
    elsif( exists $positions{$LOG} ) {
        my $count = 0;
        if( (stat $LOG)[7] < $positions{$LOG} ) {
            my($fh_old, undef) = tail_open("$LOG.1", $positions{$LOG});
            while(<$fh_old>) {
                if( m/(IN|OUT): $IP4:\d+/ ) {
                    $count = $count + 1;
                }
            }
            $positions{$LOG} = tail_close($fh_old);
        }
        my($fh, undef) = tail_open($LOG, $positions{$LOG});
        while(<$fh>) {
            if( m/(IN|OUT): $IP4:\d+\s*/ ) {
                $count = $count + 1;
            }
        }
        $positions{$LOG} = tail_close($fh);
        $positions{'count'} = $positions{'count'} + $count;
    }
    else {
        $positions{$LOG} = (stat $LOG)[7];
        $positions{'count'} = 0;
    }

    print "hits.value $positions{'count'}\n";
    if($positions{'count'} > 100000000) {
        $positions{'count'} = 0;
    }
    save_state(%positions);
}
