#!/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 "Power Supply" 2>/dev/null | 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 $status;
my $ps_seq =1;
my $perfdata = "| ";

foreach my $line (split /\n/s, $result){
	if (my @fields = split(/\|\s/,$line)){
		chomp($status = $fields[4]);
		
		if (($fields[0] =~ m/^Status\s*/g) and ($status =~ m/^Presence detected, Failure detected, Power Supply AC lost\Z/g)){
			$status_text .= "PS$ps_seq:(A/C Lost) ";
			$perfdata .= "PS$ps_seq=0 ";
			$err_lvl++;
		} elsif (($fields[0] =~ m/^Status\s*/g) and ($status =~ m/^Presence detected, Failure detected\Z/g)){
			$status_text .= "PS$ps_seq:(Fail) ";
			$perfdata .= "PS$ps_seq=0 ";
			$err_lvl++;
		} elsif (($fields[0] =~ m/^Status\s*/g) and ($status =~ m/^Failure detected, Power Supply AC lost\Z/g)){
			$status_text .= "PS$ps_seq:(Fail) ";
			$perfdata .= "PS$ps_seq=0 ";
			$err_lvl++;
		} elsif (($fields[0] =~ m/^PS Redundancy\s*/g) and ($status =~ m/^Redundancy Lost\Z/g)){
			$status_text .= "PS Redundancy Lost";
			$perfdata .= "PSR=0 ";
			$err_lvl++;
		} elsif (($fields[0] =~ m/^Status\s*/g) and ($status =~ m/^Presence detected\Z/g)){
			$status_text .= "PS$ps_seq:(OK) ";
			$perfdata .= "PS$ps_seq=10 ";
		} elsif (($fields[0] =~ m/^PS Redundancy\s*/g) and ($status =~ m/^Fully Redundant\Z/g)){
			$status_text .= "PS Fully Redundant";
			$perfdata .= "PSR=10 ";
		}
		
	}
	
$ps_seq++;
}

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

