#!/usr/bin/perl

use strict;
use Net::SNMP qw(ticks_to_time TRANSLATE_NONE);

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

my $debug = 0;

my %ups_oids = (
#default
'_default'=>'.1.3.6.1.2.1.33.1.2.3.0',
#apc
'apc'=>'.1.3.6.1.4.1.318.1.1.1.2.2.3',
#powerware
'powerware'=>'.1.3.6.1.4.1.534.1.2.1.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 = "remain=%sm;10;8;;;";
my $return_value;
my $online_min;
foreach my $key (keys %result) {
next if (!$key);
$return_value = $result{$key}{value};

next if (!defined($return_value));
$result_ok = 1;

########### check space
#apc
if ($result{$key}{vendor} eq 'apc') { $online_min = int($return_value/6000); }
#eaton
if ($result{$key}{vendor} eq 'powerware') { $online_min = int($return_value/60); }
#default
if ($result{$key}{vendor} eq '_default') { $online_min = $return_value; }

print STDERR "$key => $online_min\n" if ($debug);

#compare
if ($online_min <= 8) {
    printf("ERROR! Before switching-off ups remains %s minutes |".$perf_data."\n", $online_min,$online_min);
    exit 2;
    }

if ($online_min > 8 and $online_min<=10) {
    printf("WARNING! Before switching-off ups remains %s minutes |".$perf_data."\n", $online_min,$online_min);
    exit 1;
    }
}

if ($result_ok) {
    #print OK
    printf("OK Before switching-off ups remains %s minutes |".$perf_data."\n", $online_min,$online_min);
    exit 0;
    }

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