#!/usr/local/bin/perl

#
# pi, Sat Apr  6 23:05:15 CEST 2013
# check_quagga_bgpd_routecnt -- number of routes per peer
#
# tech/tcpip/routing/quagga/nagios-check
#

use warnings;
use strict;

use Config::Tiny;

# global variables
my($interval) = 300;
my($statefn) = '';

# variables
my($t);

# init
&readconf;

# was tun wir ?
# compare timestamp of file with now
# older than $interval
# yes: print "BGPRT CRITICAL | routes-not-updated\n"
# no: read file, print it

$t = -M $statefn;
if ( !defined($t) ) {
    print "BGP CRITICAL - statefile-not-found\n";
    exit(2);
}
$t *= 86400;
# print "mod: $t\n";
if ( $t > $interval ) {
    print "BGPRT CRITICAL - routes-not-updated\n";
    exit(2);
}

my($res) = open(INP,$statefn);
if ( !defined($res) ) {
    print "BGP CRITICAL - statefile-unreadable\n";
    exit(2);
}
my(@t) = <INP>;
chomp(@t);
close(INP);
if ( $#t > 1 ) {
    print "BGP CRITICAL - more-than-one-line-in-statefile\n";
    exit(2);
}

print $t[0]."\n";

if ( $t[0] =~ /CRITICAL/ ) {
    exit(2);
}
elsif ( $t[0] =~ /WARNING/ ) {
    exit(1);
}
exit 0;

#####################################################################

# read the config file, prepare the peer hash
sub readconf {
    my $Config = Config::Tiny->new();
    my($t);

    $Config = Config::Tiny->read( '/usr/local/etc/bmon.conf' );
    if ( !defined($Config) ) {
	print "BGP CRITICAL | Config".Config::Tiny->errstr."\n";
	exit(2);
    }

    # $interval (seconds) or greater
    $t=$Config->{_}->{interval};
    if ( defined($t) && $t > $interval ) {
        $interval = $t;
    }

    # optional
    $t=$Config->{_}->{statefile};
    if ( defined($t) ) {
        $statefn = $t;
    }
    else {
	print "BGP CRITICAL | statefile-missing-in-configfile\n";
	exit(2);
    }

}

