#!/usr/bin/perl
#
# Josh Yost
# written: 12.17.08
# updated: 12.17.08
#
# 	Use the output of /usr/sbin/showmount to create warning/critical
# signals to Nagios to verify NFS.
#
# LICENSE
#   Distributed freely w/ no license &  w/ absolutely no warranty of any kind =)
#
# BUGS & PATCHES
# 	mailto: joshyost@gmail.com
# 
# VERSIONS

use warnings;
use strict;
use File::Basename;
use Getopt::Long;
use lib "/usr/nagios/libexec";
use utils qw ( %ERRORS $TIMEOUT );

our $showmnt = '/usr/sbin/showmount';
our $exe     = basename $0;
our $vers    = '1.0.0';

#########################88### Functions ###################################
sub usage{
  print "Usage: $exe [-dhV] -H <host>\n",
        "Try '--help' for more information.\n";
  exit $ERRORS{'UNKNOWN'};
}

sub HELP{
  print "$exe\t\t$vers\n",
        "\n\tCheck that NFS is running on a host.\n",
	"\nOPTIONS\n",
        "  -d,--debug\n",                   "     Show debugging output\n",
        "  -h,--help\n",                    "     Show this help information\n",
        "  -t,--timeout\n",                 "     Set the plugin timeout\n",
        "  -V,--version\n",                 "     Show version information\n",
        "\nCAVEATS\n",
        " - This script depends on having the NFS utilities installed.\n",
        " - The executable path is hard-coded to '/usr/sbin/showmount.' Please edit the\n",
        "    '\$showmnt' variable near the top of the script for your environment.\n",
        " - You may also need to change the 'use lib' path to utils.pm for your system\n",
	"    (make sure you use an absolute path!!)\n",
	"\nEXAMPLE\n",
	"  \$ $exe -H host1\n";

  exit $ERRORS{'OK'};
}

sub VERS{
  print "$exe\t\t$vers\n";
  exit $ERRORS{'OK'};
}

$SIG{ALRM} = sub { print "ERROR - Global timeout exceeded\n"; exit $ERRORS{'UNKNOWN'} };

###### Variables
Getopt::Long::Configure("bundling");
my %opts;
GetOptions(\%opts, 'debug|d', 'help|h', 'host|H=s', 'timeout|t=i', 'version|V') || &usage();

&HELP()  if defined($opts{help});
&VERS()  if defined($opts{version});

my $DEBUG    = defined ($opts{debug});
my $host     =  $opts{host}      if defined ($opts{host});
my $timeout  = ($opts{timeout} || $TIMEOUT);

#### sanity checksy
if (! -x $showmnt){
  print "ERROR - $showmnt not found. Please edit the script for your environment.\n\n";
  &usage()
}
if (!defined($host)){
  &usage
}
&usage() if (@ARGV);

#### Prepare System Call
my $syscall = "$showmnt -e $host"; 

#### Actual syscall
# .1.3.6.1.2.1.25.1.2.0 = hrSystemDate.0
alarm $timeout;

print "debug >> syscall - $syscall 2>&1\n" if $DEBUG;

my @output = `$syscall 2>&1`;
my $state  = $?;

print "debug >> output - |@output|","debug >> state : $state\n" if $DEBUG;

alarm 0;
if ($state != 0){
	print @output;
	exit $ERRORS{'UNKNOWN'};
}
else{
  my $cnt = 0;
  for (@output){
    next if /Export list/;
    $cnt++;
  }
  print "NFS OK - $cnt shares listed.\n";
  exit $ERRORS{'OK'};
}

