#!/bin/sh
#
# NRPE passive check submission wrapper
# By Igor Gubenko (igubenko@Princeton.EDU) 05/31/2012
#

base="/usr/local/monitoring"
scripts="${base}/nagios/libexec"
handlers="${base}/nagios/libexec/eventhandlers"
gearman="${base}/mod_gearman"
logfile="${base}/log/check_nrpe_passive.log"
port=9666
timeout=120
maxrun=""

check_host () {
	tries=3
	curtry=1
	exit_stat=3
	while [[ "$exit_stat" -ne "0" ]];
	do
		if [[ "$curtry" -gt "1" ]]; then sleep 1800; fi

		res=`${scripts}/check_nrpe -p $port -t $timeout -H $host -c $command $arguments`
		exit_stat=$?

		if [[ "$curtry" -eq "$tries" ]]; then break; fi
		let "curtry+=1"
	done
#echo "##$host###$res##"
	${handlers}/submit_check_result $host "$service" $exit_stat "$res"
	if [[ "$?" -ne "0" ]]; then echo "##I ran ${handlers}/submit_check_result $host \"$service\" $exit_stat \"$res\"##"; fi
}

while getopts "f:h:m:s:c:" option
do
	case $option in
		h)
			hosts=`echo "$OPTARG" | tr ',' ' '`
			;;
		f)
			hostfile="$OPTARG"
			;;
		s)
			service="$OPTARG"
			;;
		c)
			command="$OPTARG"
			;;
		m)
			maxrun="$OPTARG"
			;;
	esac
done
shift $((OPTIND-1))

if [ ! -z "$hostfile" ]; then
	if [ ! -e "$hostfile" ]; then echo "Host file \"$hostfile\" does not exist, or is not accessible (permissions)"; exit 2; fi

	hosts_tmp=`cat $hostfile | tr '\n' ' '`
	hosts=`echo "$hosts_tmp $hosts" | sed 's/[[:space:]]*$//'`
fi

if [ -z "$service" -o -z "$command" -o -z "$hosts" ]; then
	echo "Usage: check_nrpe_passive {-h <hosts_or_ips_comma_separated> | -f <hostfile_with_hosts_or_ips_newline_separated>} -s <nagios_service_name> -c <remote_command> [-m <maximum_number_of_background_jobs_default_unlimited] [argument1 [... [argumentN]]]"
	exit 2
fi

if [ "$#" -ne "0" ]; then
	arguments="-a $*"
fi

for host in $hosts
do
	if [[ "$maxrun" != "" && "$(jobs | wc -l)" -ge "$maxrun" ]]; then wait $(jobs -l | head -1 | cut -d" " -f2); fi
	check_host &
done >>$logfile 2>&1

exit 0
