#!/bin/bash

# command[check_icinga_status]=/usr/lib/icinga/cgi/daemonchk.cgi -c 1800 -w 600

DAEMONCHK=/usr/lib/icinga/cgi/daemonchk.cgi

function usage {
	echo "Usage: $0 [-c <critical threshold in seconds>] [-w <warning threshold in seconds>] [-s <path to status.dat> ] [-l <path to lockfile>] [ -r <path to rcron state file>]"
	echo -e "\t-c\tcritical threshold in seconds"
	echo -e "\t-w\twarning threshold in seconds"
	echo -e "\t-s\tpath to status.dat"
	echo -e "\t-l\tpath to lockfile"
	echo -e "\t-r\tpath to rcron state file"
	exit 4
}

args=`getopt -a -o c:,h,w:,r:,s:,l: --long help -- "$@"`
if [ $? != 0 ] ; then
        usage
fi

PARAM=""
eval set -- "$args"
for opt ; do
        case "$opt" in
                -h|--help)
                        usage
                ;;
		-c)
			CRIT=$2
			PARAM="${PARAM} -c ${CRIT}"
			shift 2;
		;;
		-w)
			WARN=$2
			PARAM="${PARAM} -w ${WARN}"
			shift 2;
		;;
		-s)
			SOCKET=$2
			PARAM="${PARAM} -s ${SOCKET}"
			shift 2
		;;
		-l)
			LOCK=$2
			PARAM="${PARAM} -l ${LOCK}"
			shift 2
		;;
		-r)
			RCRON=$2
			shift 2
		;;
		--)
			shift
		;;
	esac
done

if [ -n "${CRIT}" ] && [ -n "${WARN}" ] ; then
	if [ "${WARN}" -ge "${CRIT}" ] ; then
		echo "Warning value can't be greater or equal then critical value!"
		exit 4
	fi
fi
if [ -n "${SOCKET}" ] && [ ! -S "${SOCKET}" ] ; then
	echo "${SOCKET} is not a socket file or can't be found!"
	exit 4
fi
if [ -n "${LOCK}" ] && [ ! -f "${LOCK}" ] ; then
	echo "${LOCK} is not a file or can't be found!"
	exit 4
fi

if [ -x "${DAEMONCHK}" ] ; then
	if [ -n "${RCRON}" ] && [ -f "${RCRON}" ] ; then
		if [ -n "`cat ${RCRON} | grep -i ^active`" ] ; then
			${DAEMONCHK} ${PARAM}
			exit $?
		fi
	else
		${DAEMONCHK} ${PARAM}
		exit $?
	fi
else
	echo "Can't execute ${DAEMONCHK}!"
	exit 4
fi
