#!/bin/bash
# vim:ts=4:sw=4:si:tw=80:isfname-==
#
###############################################
#
# Nagios script to check NIS status on a host
# 
# See usage for command line switches
#
# Author: Ian Yates (i.yates@uea.ac.uk)
# 
# Created: 2006-07-04 (i.yates@uea.ac.uk)
#
# Roy Sigurd Karlsbakk <roy@karlsbakk.net> 2010-09-20:
#
#   Added variable for nagios install path, changed the she shell to something
#   less Solarisish, later bashified the script, added som vim settings, checks
#   for includes, saner error checking (there were very little), added return
#   code 2 (unknown) in case of something wierd (or usage() called), added test
#   for -d to be required.
#
###############################################

# Set this to your nagios install
NAGIOS_PATH="/usr/local/nagios"
NAGUTILS="$NAGIOS_PATH/libexec/utils.sh"
VERSION="1.1"
FLAG_VERBOSE=FALSE
NIS_HOST=""
NIS_DOMAIN=""
RESULT=""
EXIT_STATUS=$STATE_OK

###############################################
#
## FUNCTIONS 
#

function die() {
	echo "UNKNOWN: " $@
	exit 2
}

## Print usage
function usage() {
	echo " check_nis $VERSION - Nagios NIS check script"
	echo ""
	echo " Usage: check_nis -H <hostname> -d <nis domain> [ -v ] [ -h ]"
	echo ""
	echo "		 -H  Name of host running the NIS service you wish to check"
	echo "		 -d  NIS domain"
	echo "		 -v  Verbose output"
	echo "		 -h  Show this page"
	echo
	exit 2
}
 
## Process command line options
function doopts() {
	if ( `test 0 -lt $#` )
	then
		while getopts H:d:vh myarg "$@"
		do
			case $myarg in
				'?'|'h')
					usage
					;;
				'H')
					NIS_HOST=$OPTARG
					;;
				'd')
					NIS_DOMAIN=$OPTARG
					;;
				'v')
					FLAG_VERBOSE=TRUE
					;;
				*)	# Default
					usage
					;;
			esac
		done
	else
		usage
	fi

	# check if we got what we need
	if [ "$NIS_HOST" == "" ] || [ "$NIS_DOMAIN" == "" ]; then
		echo "UNKNOWN: Need both NIS host and domain"
		exit $STATE_UNKNOWN
	fi
}


# Write output and return result
function theend() {
	echo $RESULT
	exit $EXIT_STATUS
}


#
## END FUNCTIONS 
#

# Programs needed
GREP=`which grep` || die "Can't find grep"
YPPOLL=`which yppoll` || die "Can't find ypoll"

if [ ! -f $NAGUTILS ]; then
	echo "UNKNOWN: Cant find Nagios' utils.sh $NAGUTILS: $!"
	exit $STATE_UNKNOWN
fi

#############################################
#
## MAIN 
#


# Handle command line options
doopts $@

# Do the do
OUTPUT=`$YPPOLL -h $NIS_HOST -d $NIS_DOMAIN passwd.byname 2> /dev/null | $GREP 'is supported'`
if test "$OUTPUT" != "" ; then
	RESULT="NIS OK - domain $NIS_DOMAIN"
	EXIT_STATUS=$STATE_OK
else
	RESULT="NIS CRITICAL - domain $NIS_DOMAIN not answering"
	EXIT_STATUS=$STATE_CRITICAL
fi

# Quit and return information and exit status
theend

