#!/usr/bin/perl
#
# Some hardware checks can only be done as root, so this script is designed
# to be run as a cron job, dumping useful output somewhere that can be read by
# Nagios checks.
#

use strict;
use warnings;

use Sys::Hostname;

my $OUTPUT_DIR='/var/hwchecks';
umask 0027;

our $hardware_tests;

if(-e "/opt/puppetlabs/bin/facter") {
    $hardware_tests=`/opt/puppetlabs/bin/facter -p hardware_checks`;
    chop $hardware_tests;
} else {
    exit 0;
}

foreach my $i (split /[, ]/, $hardware_tests) {
	my $OUTPUT_FILE="$OUTPUT_DIR/$i";

	if($i eq 'tw') {
		die "can't execute 3ware CLI binary" if(! -e "/usr/sbin/tw_cli.x86_64");

		my $controller = `/usr/sbin/tw_cli.x86_64 show | tail -n2`;
		$controller =~ s/(c[0-9]).*/$1/;
		$controller =~ s/\s*$//g;
		chomp($controller);
		system "/usr/sbin/tw_cli.x86_64 \"/$controller/u0 show\" > $OUTPUT_FILE";
	} elsif($i eq 'areca') {
		die "can't execute areca CLI binary" if(! -e "/usr/sbin/cli64");

		system "/usr/sbin/cli64 disk info > $OUTPUT_FILE";
		system "/usr/sbin/cli64 rsf info >> $OUTPUT_FILE";
	} elsif($i eq 'megaraid') {
		### XXX command is 'lsiutil', figure this out later
		system "touch $OUTPUT_FILE";
	} elsif($i eq 'lsi') {
		### XXX figure this out later
		system "touch $OUTPUT_FILE";
	} elsif($i eq 'cciss') {
		die "can't execute cciss_vol_status" if(! -e "/usr/sbin/cciss_vol_status");

		system "/usr/sbin/cciss_vol_status /dev/cciss/c*d0 > $OUTPUT_FILE";
    } elsif($i eq 'hpacu') {
        die "can't execute hpacucli" if(! -e "/opt/compaq/hpacucli/bld/hpacucli");

        my $slot;
        if(hostname() eq 'vesta') {
            $slot=3;
        } else {
            $slot=0;
        }

        system "/opt/compaq/hpacucli/bld/hpacucli ctrl slot=$slot show status > $OUTPUT_FILE";
        system "/opt/compaq/hpacucli/bld/hpacucli ctrl slot=$slot array all show status >> $OUTPUT_FILE";
        system "/opt/compaq/hpacucli/bld/hpacucli ctrl slot=$slot physicaldrive all show status >> $OUTPUT_FILE";
        system "/opt/compaq/hpacucli/bld/hpacucli ctrl slot=$slot enclosure all show status >> $OUTPUT_FILE";
    } elsif($i eq 'ipmi_psu') {
        die "can't execute ipmi-sensors" if(! -e "/usr/sbin/ipmi-sensors");

        system "/usr/sbin/ipmi-sensors --group='Power Supply' -q > $OUTPUT_FILE";
	} else {
		warn "unknown hardware test $i";
	}
}
