#!/bin/sh
#
# $Id$

NAGIOSHOST=nagios.domain
NAGIOSCGIURL="https://${NAGIOSHOST}/cgi-bin/cmd.cgi"

tmpfile=$(mktemp /tmp/$$.XXXXXX)
exec > $tmpfile

host_info() {
	printf "Host:\t\t$NAGIOS_HOSTNAME\n"
	printf "Address:\t$NAGIOS_HOSTADDRESS\n"

	if [ "$NAGIOS_SERVICEDESC" ]; then
		printf "Service:\t$NAGIOS_SERVICEDESC\n"
	fi
}

state_info() {
	printf "State:\t\t"
	if [ "$NAGIOS_SERVICESTATE" ]; then
		printf "$NAGIOS_SERVICESTATE"
	elif [ "$NAGIOS_HOSTSTATE" ]; then
		printf "$NAGIOS_HOSTSTATE"
	fi
	printf "\n"
}

state_detail() {
	if [ "$NAGIOS_SERVICEOUTPUT" ]; then
		printf "$NAGIOS_SERVICEOUTPUT"
	elif [ "$NAGIOS_HOSTOUTPUT" ]; then
		printf "$NAGIOS_HOSTOUTPUT"
	fi
	printf "\n"
}

alert_ack_url() {
	printf "Acknowledge this alert:\n\n"
	if [ "$NAGIOS_SERVICEDESC" ]; then
		printf "\t${NAGIOSCGIURL}?cmd_typ=34&host=${NAGIOS_HOSTNAME}&service=${NAGIOS_SERVICEDESC}\n"
	else
		printf "\t${NAGIOSCGIURL}?cmd_typ=33&host=${NAGIOS_HOSTNAME}\n"
	fi
}

ack_info() {
	printf "Who:\t\t"
	if [ "$NAGIOS_SERVICEACKAUTHOR" ]; then
		printf "$NAGIOS_SERVICEACKAUTHOR"
	elif [ "$NAGIOS_HOSTACKAUTHOR" ]; then
		printf "$NAGIOS_HOSTACKAUTHOR"
	fi
	printf "\n\n"
	
	if [ "$NAGIOS_SERVICEACKCOMMENT" ]; then
		printf "$NAGIOS_SERVICEACKCOMMENT"
	elif [ "$NAGIOS_HOSTACKCOMMENT" ]; then
		printf "$NAGIOS_HOSTACKCOMMENT"
	fi
	printf "\n"
}

case "$NAGIOS_NOTIFICATIONTYPE" in
	PROBLEM|FLAPPINGSTART)
		TAG="ALERT"

		if ! [ "$NAGIOS_CONTACTPAGER" ]; then
			host_info
			printf "\n"
			state_info
			printf "\n"
		fi

		state_detail

		if ! [ "$NAGIOS_CONTACTPAGER" ]; then
			printf "\n"
			alert_ack_url
		fi
	;;

	RECOVERY|FLAPPINGSTOP)
		TAG="OK"

		if ! [ "$NAGIOS_CONTACTPAGER" ]; then
			host_info
			printf "\n"
			state_info
			printf "\n"
		fi

		state_detail
	;;

	ACKNOWLEDGEMENT)
		TAG="ACK"
		
		if ! [ "$NAGIOS_CONTACTPAGER" ]; then
			host_info
			printf "\n"
		fi

		ack_info
	;;

	*)
		echo "invalid notification type" > /dev/stderr
		exit 1
	;;
esac

if [ "$NAGIOS_CONTACTEMAIL" ]; then
	recipient="$NAGIOS_CONTACTEMAIL"
elif [ "$NAGIOS_CONTACTPAGER" ]; then
	recipient="$NAGIOS_CONTACTPAGER"
else
	recipient=netops-notice@csub.edu
fi

subject="[${TAG}] ${NAGIOS_HOSTNAME}"
if [ "$NAGIOS_SERVICEDESC" ]; then
	subject="${subject}/${NAGIOS_SERVICEDESC}"
fi

if [ "$NAGIOS_SERVICESTATE" ]; then
	subject="${subject} ${NAGIOS_SERVICESTATE}"
elif [ "$NAGIOS_HOSTSTATE" ]; then
	subject="${subject} ${NAGIOS_HOSTSTATE}"
fi

mail -s "$subject" "$recipient" < $tmpfile
rm -f $tmpfile

exit 0
