#!/usr/bin/perl

use strict;

use vars qw($PROGNAME);
use Getopt::Long;
use vars qw($opt_h $opt_H $opt_c $opt_w @critical @warning);
my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);

# Plugin var init

my($return_code);

$PROGNAME = "$0";
sub print_help ();
sub print_usage ();

Getopt::Long::Configure('bundling');
GetOptions
    ("h"                => \$opt_h, "help"              => \$opt_h,
     "w=s"              => \$opt_w, "warning=s"         => \$opt_w,
     "c=s"              => \$opt_c, "critical=s"        => \$opt_c,
     "H=s"              => \$opt_H, "hostname=s"        => \$opt_H);

if ($opt_h) {
    print_help();
    exit 1;
}

if (!$opt_H) {
        print_usage();
        exit 1;
}

if (!$opt_w) {
        print_usage();
	exit 1;
}

if (!$opt_c) {
        $opt_c = 0;
}

my $string = "";
my $date = "";
my $rss = "";

$string = `snmpget -v1 -c public $opt_H .1.3.6.1.4.1.629.1.31.1.3.12.0`;
$date = `date +%Y.%m.%d_%k:%M:%S`;

my $tr = "";
my $cis = "";
my @hexa;
my @dec;
my @bin;

my @str = split(/ /,$string);

foreach $tr (@str) {
	if(length($tr)==2) {
		push(@hexa, $tr);
		$cis = hex($tr);
  	push(@dec, $cis);
	}
}
# hexa obsahuje pole bajtu v hex
# dec pole bajtu v dec

my $a = "";
my $cislo = 0;
my $rssi = 0;
my $bit = "";
my $teplota = "";

foreach (@dec) {
	 $a = sprintf "%b",$_;
   push(@bin, sprintf "%b", $_);
#	 $cislo = substr $_,1,1;
#	 print $cislo;
#	 print "\n";
}

$bit = sprintf("%08d", $bin[3]);
$bit = substr $bit,4,1;

if($bit) {
	$rssi = $dec[0]*100/255;
}
else {
	$rssi = $dec[0]*1300/255;
}

$teplota = sprintf("%2.2f", (($dec[2]*250/256)-50));

$rss = sprintf("%3.2f" ,$rssi);

# Plugin return code
my $status = "OK";
if ($opt_w > $rss) {
    $status = "WARNING";
    if ($opt_c < $opt_w && $opt_c > $rss) {
    $status = "CRITICAL";
    }
}

print "$status - RSSI value: $rss (Temperature: $teplota C)\n";
exit $ERRORS{$status};

sub print_usage () {
    print "\nUsage:\n";
    print "$PROGNAME\n";
    print "This Plugin is design for return RSSI from MRV device\n";
    print "\n";
    print "   -H (--hostname)   Hostname to query - (required)\n";
    print "   -c (--critical)   critical treshold - (optional)\n";
    print "   -w (--warning)    warning treshold - (required)\n";
    print "   -h (--help)       usage help\n";
}

sub print_help () {
    print_usage();
    print "\n";
}

