#!/usr/bin/perl

use strict;
use Net::SNMP;

my $TIMEOUT = 30;
$SIG{ALRM} = sub { print "ERROR: No response\n"; exit 3; };
alarm($TIMEOUT);

my $debug = 0;

my %ups_oids = (
#default ups mib
'_default'=>'.1.3.6.1.2.1.33.1.2.4',
#eaton
'powerware'=>'.1.3.6.1.4.1.318.1.1.1.2.2.1.0',
#eaton 9PX3000i RT 2U
'eaton'=>'.1.3.6.1.4.1.534.1.2.4.0',
);

exit if (!$ARGV[0]);

my $hostip=$ARGV[0];

my ($session, $error) = Net::SNMP->session(
   -hostname  => shift || $hostip,
   -community => shift || 'public',
   -port      => shift || '161',
   -timeout   => 5,
   -version   => shift || '1',
);

if (!defined($session)) { printf("ERROR: %s.\n", $error); exit 1; }

my %result;
foreach my $key (sort keys %ups_oids) {
my $key_oid = $ups_oids{$key};
my $ret = $session->get_request( -varbindlist => [$key_oid] );
my $value;
if (!$ret) {
    #search in subtree
    $ret = $session->get_next_request( -varbindlist => [$key_oid] );
    my @keys_next = keys %$ret;
    if (scalar @keys_next and $keys_next[0]) {
        my $get_key = $keys_next[0];
        if ($get_key=~/^$key_oid/) {
            $value = $ret->{$get_key};
            print STDERR "Get-Next for key $key_oid: $get_key => $value\n" if ($debug);
            }
        }
    } else {
    $value = $ret->{$key_oid};
    print STDERR "Get: $key_oid => $value\n" if ($debug);
    }
next if (!defined($value));
$result{$key_oid}{value}=$value;
$result{$key_oid}{vendor}=$key;
last;
}

$session->close;

if (!%result) { printf("OK: Unknown model. \n"); exit 0; }

my $result_ok = 0;
my $perf_data = "charge=%s%%;50;30;;;";
my $return_value;
foreach my $key (keys %result) {
next if (!$key);
$return_value = $result{$key}{value};
next if (!defined($return_value));
$result_ok = 1;

########### check temp

if ($return_value < 60 and $return_value > 30) {
    printf("WARNING! Charge of batteries: %s percents |".$perf_data."\n",$return_value,$return_value);
    exit 1;
    }
if ($return_value <= 30) {
    printf("ERROR! Charge of batteries: %s percents |".$perf_data."\n",$return_value,$return_value);
    exit 2;
    }
}

if ($result_ok) {
    #print OK
    printf("OK. Charge of batteries %s percents |".$perf_data."\n", $return_value,$return_value);
    exit 0;
    }

printf("WARNING! You shouldn't have seen this. If you still see it, something clearly went wrong.\n");
exit 3;
