#!/usr/bin/perl

use strict;
use Net::SNMP;
use Getopt::Long qw(:config no_ignore_case);

my %opt;
GetOptions( "H=s" => \$opt{'H'},
				"C=s" => \$opt{'C'},
				"p=s" => \$opt{'p'},
				"idle=s" => \$opt{'idle'},
				"connect=s" => \$opt{'connect'},
				"active=s" => \$opt{'active'},
				"opensent=s" => \$opt{'opensent'},
				"openconfirm=s" => \$opt{'openconfirm'},
				"established=s" => \$opt{'established'} );


my %bgp_states = (
   "1" => "Idle",
   "2" => "Connect",
   "3" => "Active",
   "4" => "OpenSent",
   "5" => "OpenConfirm",
   "6" => "Established"
);

unless ($opt{'H'} && $opt{'C'} && $opt{'p'} && $opt{'idle'} && $opt{'connect'} && $opt{'active'} && $opt{'opensent'} && $opt{'openconfirm'} && $opt{'established'}) {
	print "Usage: $0 <ARGS>\n";
	print "Example: $0 -H 192.168.0.1 -C public -P 192.168.1.2 \\\n";
	print "            -idle c -connect w -active w -opensent w -openconfirm w -established o\n\n";
	print " -H\t\t Hostname or IP\n";
	print " -C\t\t Community String\n";
	print " -p\t\t Peer IP Address\n";
	print " -idle\t\t BGP State Idle,\t c=critical, w=warning, o=ok\n";
	print " -connect\t BGP State Connect,\t c=critical, w=warning, o=ok\n";
	print " -active\t BGP State Active,\t c=critical, w=warning, o=ok\n";
	print " -opensent\t BGP State OpenSent,\t c=critical, w=warning, o=ok\n";
	print " -openconfirm\t BGP State OpenConfirm,\t c=critical, w=warning, o=ok\n";
	print " -established\t BGP State Established,\t c=critical, w=warning, o=ok\n\n";
	exit 3;
}
$opt{'idle'} = cl($opt{'idle'});
$opt{'connect'} = cl($opt{'connect'});
$opt{'active'} = cl($opt{'active'});
$opt{'opensent'} = cl($opt{'opensent'});
$opt{'openconfirm'} = cl($opt{'openconfirm'});
$opt{'established'} = cl($opt{'established'});

my $oid_bgp_peerstate = '1.3.6.1.2.1.15.3.1.2.'.$opt{'p'};

my($session, $error) = Net::SNMP->session(-hostname => $opt{'H'},
														-community => $opt{'C'} );

unless(defined($session)) {
	print "Could not establish SNMP session\n";
	exit 2;
}


my $result = $session->get_request(-varbindlist => [$oid_bgp_peerstate] );
my $bgp_peerstate = $result->{$oid_bgp_peerstate};

$session->close;

print "BGP Peer ".$opt{'p'}." State: ".$bgp_states{$bgp_peerstate}."\n";

print $opt{'established'};

exit $opt{'established'} if $bgp_peerstate == 6;
exit $opt{'openconfirm'} if $bgp_peerstate == 5;
exit $opt{'opensent'} if $bgp_peerstate == 4;
exit $opt{'active'} if $bgp_peerstate == 3;
exit $opt{'connect'} if $bgp_peerstate == 2;
exit $opt{'idle'} if $bgp_peerstate == 1;
exit 3;


sub cl {
	my($level) = @_;

	return 2 if $level eq "c";
	return 1 if $level eq "w";
	return 0 if $level eq "o";
	return 3;
}
