#! /usr/bin/perl -w
use strict;
use Net::SNMP;
use Getopt::Std;
use vars qw/$opt_h $opt_C $opt_t $opt_w $opt_c/;
# use Data::Dumper;

sub usage {
   print <<EOF;

Usage:
$0 -h host -C community -w percentage -c percentage
 -h host : hôte cible
 -C community : communauté SNMP utilisée
 -w percentage : pourcentage qui d'utilisation CPU qui déclenche une alarme warning (0 -> 100)
 -c percentage : pourcentage qui d'utilisation CPU qui déclenche une alarme critical (0 -> 100)

EOF
   exit(3);
}

getopt("h:C:w:c:");
my $host = $opt_h || usage();
my $community = $opt_C || usage();
my $warning_level = $opt_w || usage();
my $critical_level = $opt_c || usage();

$warning_level =~ /\d+/ || usage();
$critical_level =~ /\d+/ || usage();

if (! ( $warning_level > 0 && $warning_level < 100 ) ) {
    usage();
}

if (! ( $critical_level > 0 && $critical_level < 100 ) ) {
    usage();
}

#
# Dans B2R07603B_MIB.txt, MIB FOUNDRY-SN-ROOT-MIB :
# enterprises.foundry.products.switch.snAgentSys.snAgentGbl.snAgGblCpuUtil1MinAvg.0
#            =
#         .1.3.6.1.4.1.1991.1.1.2.1.52.0


my $cpu_util_oid = ".1.3.6.1.4.1.1991.1.1.2.1.52.0";

my ($session, $error) =
   Net::SNMP->session(-hostname => $host, -version => 1, -community => $community);

if (not defined($session)) {
   print "Impossible d'ouvrir une session SNMP avec $host: $error !\n";
   exit(3); # UNKNOWN
}

my $result = $session->get_request(-varbindlist => [ $cpu_util_oid ]);

if (not defined($result)) {
    my $error = $session->error();
    print "Impossible de récupérer l'utilisation CPU sur $host : $error\n";
    exit(3); # UNKNOWN
}

my $cpu_utilization = $result->{$cpu_util_oid};

if ( $cpu_utilization > $critical_level ) {
    print "CRITICAL: $cpu_utilization% CPU\n";
    exit(2); # CRITICAL
}

elsif ( $cpu_utilization > $warning_level ) {
    print "WARNING: $cpu_utilization% CPU\n";
    exit(1); # WARNING
}

else {
    print "OK: $cpu_utilization% CPU\n";
    exit(0); # OK
}


