#!/usr/bin/perl

#
# check_x4600_overheat.pl
# Check if Sun X4600 M2 server is overheated
# this machine has a builtin threshold for CPU ambient temperature,
# warning if T > 38C, 
# critical and machine shutdown if T > 45C
# plugin checks ambient temperature sensors using IMPI ipmitool
# 
# $Id: check_x4600_overheat.pl 51 2010-06-22 05:44:33Z mit $
# (C) Andrey Mitroshin <mit@akamit.com>
# Released under the GNU General Public License (GPL)
#

use warnings;
use strict;

use lib "/usr/local/nagios/libexec";
use utils qw($TIMEOUT %ERRORS &print_revision);
use vars qw($opt_V $opt_v $opt_h $verbose $opt_w $opt_c);
use Getopt::Long;
 
my $default_warning = 30;
my $default_critical = 35;

Getopt::Long::Configure('bundling');
GetOptions("V" => \$opt_V, "version" => \$opt_V,
         "h" => \$opt_h, "help" => \$opt_h,
         "v" => \$opt_v, "verbose" => \$opt_v,
         "w=i" => \$opt_w, "warning=i" => \$opt_w,
         "c=i" => \$opt_c, "critical=i" => \$opt_c);

if (defined $opt_V) { print_revision($0,'1.0'); exit $ERRORS{'OK'}; }
if (defined $opt_h) { print_help(); exit $ERRORS{'OK'}; }

if (not defined $opt_w) { 
	$opt_w = $default_warning;
	print "defaulting -w to $default_warning", "\n" if defined $opt_v;
}

if (not defined $opt_c) { 
	$opt_c = $default_critical;
	print "defaulting -c to $default_critical", "\n" if defined $opt_v;
}


open IPMI, "ipmitool sdr type temperature |" or die "ipmitool: $!";

while (my $line = <IPMI>) {
	chomp $line;
	unless ($line =~ /^(.*) \| (.*) \| (.*) \| (.*) \| (.*)$/) {
		die "Bad ipmitool output format: $line";
	}

	my $name  = trim($1);
	my $temp = trim($5);
	if ($name =~ /^p(\d+)\.t_amb$/) {
		if ($temp =~ /^(\d+) degrees C$/) {
			my $temp_v = $1;
			if ($temp_v >= $opt_c) {
				print "CRITICAL: $name t_amb is $temp_v", "\n";
				exit $ERRORS{'CRITICAL'};
			}
			if ($temp_v >= $opt_w) {
				print "WARNING: $name t_amb is $temp_v", "\n";
				exit $ERRORS{'WARNING'};
			}
		}
	}
}

print "t_amb of all cpus is ok", "\n";
exit $ERRORS{'OK'};

#
# strip leading and trailing space characters
#
sub trim {
        my $v = shift;
        $v =~ s/^\s+//;
        $v =~ s/\s+$//;
        return $v;
}

sub print_help  {
        print "\n";
        print_usage();
        print <<EOT;
$0
Check Sun X4600 M2 machine CPU ambient temperature sensors using IPMI.
License: GPL

-h, --help
   print this help message
-c, --critical=THRESHOLD
   critical temperature threshold (default: $default_critical)
-w, --warning=THRESHOLD
   warning temperature threshold (default: $default_warning)
EOT
}

sub print_usage {
        print "Usage: $0 [-w <warning>] [-c <critical>]\n";
}
