#!/usr/bin/perl

use strict;
use Getopt::Std;
use vars qw($opt_h);

getopts('h');

# Written by Joe Chlanda joe.chlanda@dreamhost.com for the Dc-Ops-Dashboard
# This script runs locally on a host and if ipmitool is found it reports
# all lines with the word degrees in it to nagios for later sorting.

# Usage Instructions -h
if ( $opt_h ) {
	print "Usage: $0 \n";
	print "This script pulls all temperature values from ipmitool and sends them in one nagios module (temerature) \n";
	exit;
}

sub exitreport {
	my $status = shift;
	my $message = shift;

	my $result = "OK" if $status == 0; # OK
	$result = "CRITICAL" if $status == 2; # Critical
	$result = "UNKNOWN" if $status == 3; # UNKNOWN
	print $message . "\n";
	exit $status;
} # End sub exitreport

my $status = '0'; # 0 = Ok until proven bad
my $result = ''; # Blank output until amended

my $ipmi = "/usr/bin/ipmitool";
my $command = $ipmi ." sdr elist full 2>/dev/null | grep degrees";
# Lets preform a check and make sure ipmitool actually exist eh?
(-e $ipmi) || exitreport('2',"error: ipmitool does not exist");

my $output = qx($command);
my $exitcode = $? >> 8;
if ($exitcode >= 1) {
	$status = 3;
	$result = "ipmi not found";
} else {
	my @lines = split /\n/, $output; # Splits output on new lines
	foreach my $line (@lines) {
		$line =~ s/\h+/ /g; # Removes extra white spaces
		my @split = split /\Q|/, $line; # Splits on special characher "|"
		$result .= $split[0] . " - " . $split[4] . " :: "; # Prints the first and fourth output of array "Name" (AMBIENT_TEMP) and Value (21 degrees C)
	} # End foreach my $line
}

exitreport($status, $result);
