#!/usr/bin/perl
# Check temperature of Temperature@lert devices against the device's configuration
# requires install of XML-Parser and Data::Dumper
#
# By Cipher-0 (Steve Kleine)
# notavalid@hotmail.com (yes, that's the address)
# Licence GPLv2

# use modules
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

#basics

my(%ERRORS) = ( OK=>0, WARNING=>1, CRITICAL=>2, UNKNOWN=>3 );
my $ErrorReturn = $ERRORS{OK};
my $Message = "OK";

# helpfile

sub printhelp () {
        print "Usage: check_tempalert RSS_FEED_URL \n";
        "\t This pulls statuses from the unit itself; best have it configured right!\n";
}

my ($HOST) = @ARGV;
chomp $HOST;

# create object
my $xml = new XML::Simple;

#get XML and write

`wget $HOST --output-file=/dev/null --output-document=/tmp/xmlfeed.rb` ;

# read XML file

my $data = $xml->XMLin("/tmp/xmlfeed.rb");

#print Dumper($data); #debug

#Now, how to pull the data
my $temperature = $data->{ports}->{port}->{condition}->{currentReading};
my $temp_min = $data->{ports}->{port}->{condition}->{lowLimit};
my $temp_max = $data->{ports}->{port}->{condition}->{highLimit};
my $unit_error = $data->{errorReadingSensor};
my $alarm_status = $data->{ports}->{port}->{condition}->{alarmStatus};
my $temp_units = $data->{tempUnits};

#error logic

if ($unit_error == $ERRORS{WARNING}) {
	$ErrorReturn = $ERRORS{UNKNOWN};
	$Message = "UNKNOWN";
}

elsif (($temp_min > $temperature) &&  ($alarm_status == 1)) { #too low
	$ErrorReturn = $ERRORS{CRITICAL};
	$Message = "CRITICAL";
	}

elsif (($temp_max < $temperature) &&  ($alarm_status == 1)){ #too high
	$ErrorReturn = $ERRORS{CRITICAL};
	$Message = "CRITICAL";
}

#printing for debugs
#print "$temperature is the current temp.\n\t$temp_min is the minimum temp acceptable.\n\t$temp_max is the maximum temp acceptable.\n\t $unit_error is the unit status.";
#print "Current temp is $data->{ports}->{port}->{condition}->{currentReading} F\n"; #returns the decimal representation of the temperature

print "$Message: $temperature $temp_units\n";
exit $ErrorReturn;
