#! /usr/bin/perl
# Check NFS share access using showmount -e
# anders@fupp.net, 2010-06-21

use Getopt::Std;

getopts('H:s:a:');
$ENV{"PATH"} = $ENV{"PATH"} . ":/usr/bin:/sbin";

sub usage {
	print "Usage: check_nfs_share -H <hostname> -s <share> [-a <check access for this host>]\n";
	exit(3);
}

usage unless ($opt_H && $opt_s);

foreach $line (`showmount -e $opt_H 2>/dev/null`) {
	# Strip newlines
	chomp($line);
	# Strip whitspace at end of line
	$line =~ s@\s+$@@;

	if ($line =~ /(\/[\w\.\/]+)\s+(.+)/) {
		$share = $1;
		$hosts = $2;
		if ($share =~ /$opt_s/) {
			if ($opt_a) {
				if (grep(/$opt_a/, split(/\s+/, $hosts))) {
					print "Share $opt_s exists on $opt_H and is accessible by $opt_a (hosts=$hosts).\n";
					exit(0);
				} else {
					print "Share $opt_s exists on $opt_H but is not accessible by $opt_a (hosts=$hosts).\n";
					exit(0);
				}
			} else {
				print "Share $opt_s exists on $opt_H.\n";
				exit(0);
			}
		}
	}
}

print "Did not find share $opt_s on $opt_H.\n";
exit(2);
