#!/bin/sh -e


nscabin="/usr/sbin/send_nsca"

err=0
error() {
	trap '' EXIT
	errc=$?
	echo "ERROR: $@"
	exit $errc
}

usage() {
	echo -e "$0 -H <nscahost> -h <hostname> -s <service> [ -c <nsca_config> ] <check_command>"
	echo -e "\t-H NSCA daemon hosting machine"
	echo -e "\t-h monitored host_name as in nagions configuration"
	echo -e "\t-s monitored service_description as in nagios configuration"
	echo -e "\t-c send_nsca.cfg file (default: /etc/send_nsca.cfg )"
	trap '' EXIT
	exit 0
}
trap error EXIT

[ $# -eq 0 ] && usage

while getopts "c:H:h:s:" options; do
	case "$options" in
		c)
			config=$OPTARG;;
		H)
			nscahost=$OPTARG;;
		h)
			hostname=$OPTARG;;
		s)
			service=$OPTARG;;
		*)
			usage
			exit 3
			;;
	esac
done
shift $(($OPTIND-1))

config=${config:-/etc/send_nsca.cfg}

[ -r "$config" ] || error "cannot read $config configuration file"
[ "$nscahost" ] || error "no NSCA host given, use -H <nscahost>"

[ "$hostname" ] || { err=1; echo "WARNING: no hostname given, using hostname --fqdn"; }
hostname=${hostname:-`hostname --fqdn`}

[ "$service" ] || error "no service_description given, use -s <service_description"

[ "$1" ] || error "no check_command nor argument given"
which "$1" >/dev/null 2>&1 || error "$1 doesn't look like an executable file"
[ -x "$nscabin" ] || error "couldn't find send_nsca binary"

set +e
output=`$@`
retc=$?
nscaoutput=`echo -e "$hostname\t$service\t$retc\t$output" | $nscabin -H "$nscahost" -c "$config" 2>&1`
errc=$?

err=`expr $err + $errc`

if [ $err -ne 0 ]; then
	echo $nscaoutput
fi

trap '' EXIT
exit $err
