#!/bin/sh

# Arguments for service:
#  $1 = host_name (Short name of host that the service is
#       associated with)
#  $2 = svc_description (Description of the service)
#  $3 = state_string (A string representing the status of
#       the given service - "OK", "WARNING", "CRITICAL"
#       or "UNKNOWN")
#  $4 = plugin_output (A text string that should be used
#       as the plugin output for the service checks)
#  $5 = perfdata
#

# Arguments for host:
#  $1 = host_name (Short name of host we check for status)
#  $2 = state_string (A string representing the status of
#       the given service - "OK", "DOWN", "UNREACHABLE"
#       or "UNKNOWN")
#  $3 = plugin_output (A text string that should be used
#       as the plugin output for the host checks)
#  $4 = perfdata
#

if [ "$#" = 5 ]; then
	TYPE=SERVICE
	CODE=$3
elif [ "$#" = 4 ]; then
	TYPE=HOST
	CODE=$2
else
	echo >&2 "You must specify exactly 4 or 5 arguments"
	exit 1
fi

CENTRAL=$(awk '!/#/ { print }' /etc/nagios/send_nsca-central)

if [ -z $CENTRAL ]; then
	echo >&2 "You must specify nagios NSCA host in /etc/nagios/send_nsca-central"
	exit 1
fi

# Convert the state string to the corresponding return code
RETURN_CODE=3

case "$CODE" in
	OK)
		RETURN_CODE=0
		;;
	WARNING)
		RETURN_CODE=1
		;;
	DOWN)
		RETURN_CODE=1
		;;
	CRITICAL)
		RETURN_CODE=2
		;;
	UNREACHABLE)
		RETURN_CODE=2
		;;
	UNKNOWN)
		RETURN_CODE=3
		;;
	[0-3])
		RETURN_CODE="$CODE"
		;;
esac

# pipe the service check info into the send_nsca program, which
# in turn transmits the data to the nsca daemon on the central
# monitoring server

if [ "$TYPE" = "SERVICE" ]; then
	echo -e "$1\t$2\t$RETURN_CODE\t$4|$5\n" | /usr/sbin/send_nsca $CENTRAL -c /etc/nagios/send_nsca.cfg
elif [ "$TYPE" = "HOST" ]; then
	echo -e "$1\t$RETURN_CODE\t$3|$4\n" | /usr/sbin/send_nsca $CENTRAL -c /etc/nagios/send_nsca.cfg
else
	echo >&2 "This cannot happen"
	exit 1
fi
