#!/usr/bin/perl
use strict;
use warnings;

use POSIX ();

my ($sysname, $nodename, $release, $version, $machine);
($sysname, $nodename, $release, $version, $machine) = POSIX::uname();

if ($sysname eq "FreeBSD") {
        use lib "/usr/local/libexec/nagios";
} else {
        use lib "/usr/local/nagios/libexec";
}

use utils qw(%ERRORS);

my $usage = "
Usage: $0 host_addr ipmi_user ipmi_pass

Connects to a Dell BMC and parses the Drive token for RAID status
and disk slot errors.";

# Gets output of ipmi command, this is funny with IPMI v2, we *sometimes* get an Authentication type error.
if (my $result = `/usr/local/bin/ipmitool -I lan -H $ARGV[0] -U $ARGV[1] -P $ARGV[2] sdr type "Fan" | grep -v "Authentication"`) {
# Check for authentication type error, and ignore it if it's there.

# XXX Debug lines XXX
#print "Raw Status: $result\n";
#print "My Status = \"$status[4]\"\n";

my $status_text = "";
my $err_lvl = 0;
my $disabled = 0;
my $status;
my $perfdata = "| ";

foreach my $line (split /\n/s, $result){
	if (my @fields = split(/\|\s/,$line)){
		chomp($status = $fields[4]);
		my @fan_label = split( /\s/s, $fields[0]);
		
		if ($status =~ m/^(\d*)\sRPM\Z/g){
			if ($1 == 0 ){
				$err_lvl++;
			} else {
				$status_text .= "$fan_label[1]:($1) ";
			}
			$perfdata .= "fan$fan_label[1]=$1 ";
		} elsif ($status =~ m/^Disabled\Z/g){
			$disabled++;
		} elsif ($status =~ m/^Redundancy Lost\Z/g){
			$status_text .= "$fields[0]:($status) ";
			$err_lvl++;
		} else {
			$status_text .= "$fan_label[1]:($status) ";
		}
	}
	
}

if ($err_lvl > 0) {
	print "CRITICAL: $status_text\b, $disabled fan sensors disabled. $perfdata\n";
	exit $ERRORS{'CRITICAL'}
} else {
	print "NORMAL: $status_text\b, $disabled fan sensors disabled. $perfdata\n";
	exit $ERRORS{'OK'}
}
} else {
	die $usage;
}

