#!/bin/sh
#
# Copyright (c) 2013 Holger Weiss <holger@weiss.in-berlin.de>
#
# This file is free software; Holger Weiss gives unlimited permission to copy
# and/or distribute it, with or without modifications, as long as this notice is
# preserved.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY, to the extent permitted by law; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

set -u

send_nsca_args=${SEND_NSCA_ARGS:+$SEND_NSCA_ARGS}

PATH="$PATH:/usr/local/nagios/libexec:/usr/lib/nagios/plugins"
export PATH

die()
{
	echo >&2 "$@"
	exit 1
}

usage()
{
	die "Usage: $0 [-c <config-file>] [-H <host>] [-S <service>]" \
	    "<plugin> [<argument> ...]"
}

while getopts c:H:hS: option
do
	case $option in
	c)
		send_nsca_args="${send_nsca_args:+$send_nsca_args }-c $OPTARG"
		;;
	H)
		host=$OPTARG
		;;
	S)
		service=$OPTARG
		;;
	h|\?)
		usage
		;;
	esac
done

shift `expr $OPTIND - 1`
test $# -ge 1 || usage

host=${host:-`hostname | sed 's+\..*++' | tr '[:upper:]' '[:lower:]'`}
service=${service:-`echo "$1" | sed 's+.*[_/]++' | tr '[:lower:]' '[:upper:]'`}
output=`"$@"`
state=$?

test $state -le 3 || die "$0: '$@' yields invalid plugin return code $state"

printf '%b' "$host\t$service\t$state\t$output\n" | send_nsca $send_nsca_args

# vim:set joinspaces noexpandtab textwidth=80:
