#!/usr/bin/perl
# Copyright: Benjamin Grosse, 2013
#
# This script checks temperture by reading /sys/class/thermal
#
#

use Nagios::Plugin;

$np = Nagios::Plugin->new( 
	shortname => "SysTemp",
	usage => "Usage: %s [-w] [-c] ",
	 );

$np->add_arg(
	spec => "warning|w=s",
	help => "-w, --warning=INTEGER:INTEGER. Warning if system temperature is over INTEGER:INTEGER",
	);

$np->add_arg(
	spec => "critical|c=s",
	help => "-c, --critical=INTEGER:INTEGER. Critical if system temperature is over INTEGER:INTEGER",
	);

$np->getopts;

## Reading thermal zones and temperatures
use constant PathToThermal => '/sys/class/thermal';

opendir my($dh), PathToThermal or $np->nagios_exit( UNKNOWN, "Could not open dir $name" );
@files = readdir $dh;
@files = grep m/thermal_zone/, @files;


foreach my $name (@files) {
	$name = PathToThermal .'/'. $name .'/temp';
	open(FH, $name) or $np->nagios_exit( UNKNOWN, "Could not open file $name" );
	sysread FH, $temp, 32;
	close(FH);
	$temp = $temp/1000;
	if ($maxTemp < $temp){
		$maxTemp = $temp;
	}
	push @temperatures, ($temp);	
}

foreach(@temperatures) {
	$line = $line. "$_" . '°C ';
}

if(!(scalar @temperatures)) {
	$np->nagios_exit( UNKNOWN, "No temperatures found" );
}

$threshold = $np->set_thresholds( warning => $np->opts->warning, critical => $np->opts->critical );
$np->add_perfdata(
	label => "Temp",
	value => $maxTemp,
	threshold => $threshold,
	uom => "", # Bug in Nagios::Plugin version 0.15
	);

$np->nagios_exit( 
	return_code => $np->check_threshold($maxTemp),
	message => "system temperature(s): $line",
	);
