#!/usr/bin/perl -w

# check_metastat Nagios Plugin - Version 1.0
# Last Updated: 5/12/2003
#
# Report any bugs/questions to Russell Scibetti at nagios@quadrix.com

use Getopt::Long;
&Getopt::Long::config('bundling');

#YOU MUST SET YOUR PATH PROPERLY!
$ENV{PATH} = "/usr/opt/SUNWmd/sbin:/usr/sbin:$ENV{PATH}";

GetOptions
        ("V"   => \$version,    "version"       => \$version,
         "h"   => \$help,       "help"          => \$help,
         "v"   => \$verbose,    "verbose"       => \$verbose,
         "e=s" => \$error,       "error=s"	=> \$error);

if ($version) {
  printVersion();
  exit 3;
}

if ($help) {
  printVersion();
  printHelp();
  exit 3;
}

if (!$error) {
 $error = "Matinenance|Error";
} 

my $disk = "";
my $cmd = "metastat";

foreach $_ (`$cmd`) {
  chomp;
  if (/$error/) {
    $failure = 1;
    if (!(/State:/)) {
      @data = split;
      if ($disk) {
        $disk .= ", $data[0]";
      }
      else {
        $disk = $data[0];
      }
    }
  }
  $lastline = $_;
}

$exitcode = $? >> 8;

if ($exitcode == 0) {

  if ($failure) {
    if ($disk) {
      printf "CRITICAL - Error on disk $disk\n";
      exit 2;
    }
    else {
      printf "CRITICAL - MetaStat Disk Error Found\n";
      exit 2;
    }
  }
  else {
    printf "OK - No Disk Errors\n";
    exit 0;
  }
}
else {
  printf "Metastat command error: $lastline\n";
  exit $exitcode;
}

################################
#
# Version and Help Information
#
################################

sub printVersion {
  printf <<EndVersion;
$0 (nagios-plugins) 1.0
The nagios plugins come with ABSOLUTELY NO WARRANTY. You may redistribute
copies of the plugins under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.
EndVersion
}

sub printHelp {
  printf <<EOF;

This plugin runs the metastat command and looks for any disk in an error state.

Usage: $0 (-e <Error RegEx>)
       $0 --help
       $0 --version
NOTE: -H and -C must BOTH be specified

Options:

 -e, --error=<Error RegEx>
   Regular Expression to match for as an Error
   (Default = "Maintenance|Error")
 -v, --verbose
   Show each line of output from metastat
 -h, --help
   Print detailed help screen
 -V, --version
   Print version information

EOF
}

