#!/usr/bin/perl -w
use strict;
# huw@munted.org 2004
# based on check_em01.pl from http://nagios.sourceforge.net/download/contrib/plugins/esensors/esensors.tar.gz
# required lib-www-perl

use LWP;
use Getopt::Long;


my %opts;
GetOptions (\%opts, 'h=s', 'tw=s', 'tc=s', 'hw=s', 'hc=s', 'iw=s', 'ic=s');
useage() if  !$opts{h};

my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new(GET=>'http://'.$opts{h}.'/index.html?em123456');
my $response = $ua->request($request);
my %results;
if ($response->is_success) {
	my $resp = $response->content;
	if ($resp =~ /E01.*TF\D*([0123456789.]+)\D*HU\D*([0123456789.]+)\D*IL\D*([0123456789.]+)/g) {
        $results{temperature}=$1;
        $results{humidity}=$2;
        $results{illumination}=$3;
    }
}
if (!$results{temperature} || !$results{humidity} || !$results{illumination}) {
	die "Got no data back from the sensor\n";
}
else {
	$results{temperature} =~ s/_//g;
	$results{temperature} = sprintf("%.1f", (5*($results{temperature}-32))/9);
	#$results{temperature} = sprintf("%.1f", $results{temperature});  # format
	$results{humidity} = sprintf("%.1f", $results{humidity});  # format
	$results{illumination} = sprintf("%.1f", $results{illumination});  # format
	$results{humidity} =~ s/[_%]//g;
	$results{output} = "temp: $results{temperature} C, humidity: $results{humidity}\%, illumination: $results{illumination}";
}

my $warning;
my $critical;
check_thresh($opts{tc}, $results{temperature}, 'CRITICAL');
check_thresh($opts{tw}, $results{temperature}, 'WARNING');
check_thresh($opts{hc}, $results{humidity}, 'CRITICAL');
check_thresh($opts{hw}, $results{humidity}, 'WARNING');
check_thresh($opts{ic}, $results{illumination}, 'CRITICAL');
check_thresh($opts{iw}, $results{illumination}, 'WARNING');

if (defined $critical) {
	print "CRITICAL: $results{output}\n";
	exit 2;
}
elsif (defined $warning) {
	print "WARNING: $results{output}\n";
	exit 1;
}
else {
	print "OK: $results{output}\n";
	exit 0;
}

# should never get here
die "Something has gone really wrong\n";

### Subs ###
sub check_thresh {
	my $user_thresh = $_[0];
	my $value = $_[1];
	my $level = $_[2];
	my ($hi,$lo) = split (/\,/, $user_thresh) if (defined $user_thresh);
	if (defined $hi || defined $lo) {
		if ($level eq 'WARNING') {
			$warning = 1 if (($value > $hi) || ($value < $lo));
		}
		elsif ($level eq 'CRITICAL') {
			$critical = 1 if (($value > $hi) || ($value < $lo));
		}
	}
	else {
		die "Did not get min/max values\n";
	}
}	

sub useage {
	die  "Usage: $0 -h hostname -tc hi,low -tw hi,low -hc hi,low -hw hi,low -ic hi,low -iw hi,low\n";
}
