#!/bin/sh
#
# filename: check_vdrsignalstrength.sh
# History:
#  0.3   20191001 - use STRG (femon v2.4.0) instead of SNRA (femon v2.2.1)
#  0.2   20170605 - use input parameters (by wagner-thomas@gmx.at)
#  0.1.1 20140822 - replace CLOSE with QUIT, added -n check
#  0.1   20090525 - Creation / LGS aka Heinzharald
#  0.02  20090531 - Included CRIT value in in/output
#                  Check correct card
# Synopsis:
#  NAGIOS plugin that checks VDR femon plugin in order
#  to assure sufficient signal-noise-ratio.
# TODO:
#  - Cycle through all available cards (via NEXT/PREV commands)
#  - More sophistication? E.g. detect tuned channel (SNR will
#    vary per channel.
#  - Catch CRITICAL states
#  - "Correct" handling of CRIT limit

MYWARN=90
MYCRIT=80
# Number of cards in system, beginning with "0"
MYCARDS=0

# NAGIOS' wanted return values
NAG_OK=0
NAG_WARN=1
NAG_CRIT=2
NAG_UNKNOWN=3

usage() {
cat <<EOF
This script checks the singal streng as STRG on a vdr with femon plugin via svdrpsend.
OPTIONS:
 -h	Show this message
 -H	host on which vdr with femon plugin is running (defaults to localhost)
 -p	port of svdrpsend (defaults to 6419)
 -w	warning level (defaults to 90)
 -c	critical level (default to 80)
 -C	card number to check
EOF
}

while getopts ":H:w:c:C:h" OPTION
do
	case $OPTION in
		h) 	usage
			exit $NAG_CRIT
			;;
		H) MYHOST=$OPTARG
			;;
		P) MYPORT=$OPTARG
			;;
		w) MYWARN=$OPTARG
			;;
		c) MYCRIT=$OPTARG
			;;
		C) MYCARDS=$OPTARG
			;;
		?) usage
			exit $NAG_UNKNOWN
	esac
done

if [ ! -x "/usr/bin/svdrpsend" ]; then
	echo "UNKNOWN - /usr/bin/svdrpsend is not executable"
	exit $NAG_UNKNOWN
fi

# construct svdrpsend command with optional hostname and port
MYSVDRP="/usr/bin/svdrpsend ${MYHOST+-d ${MYHOST}} ${MYPORT+-p ${MYPORT}}"
echo $MYSVDRP

# Need to run this to catch error states of plugin.
# These could be that femon is listening/tuned to a card
# that is actually not installed e.g. #8.
# So, what card are we tuned to?
curcard=`$MYSVDRP PLUG femon STRG | sed -n -e 's#.*\#\([0-9]\+\).*#\1#p'`

# Card should be 0 to x depending on cards in VDR,
# currently sufficient if tuned to one of the installed ones.
if [ $curcard -gt $MYCARDS ]; then
        $MYSVDRP PLUG femon OPEN | fgrep -e Error
        $MYSVDRP PLUG femon QUIT | fgrep -e Error
fi
               
# sed is your friend
b=$($MYSVDRP PLUG femon STRG | grep 900 | awk '{print $2}')

if [ -n $b ]; then
	if [ $b -ge $MYWARN ]; then
		echo -n "OK"
	        EX=$NAG_OK
	elif [ $b -ge $MYCRIT ]; then
		echo -n "WARNING"
		EX=$NAG_WARN
	else
		echo -n "Critical"
		EX=$NAG_CRIT
	fi
	echo " - STRG=$b;warning=$MYWARN;critical=$MYCRIT|STRG=$b;$MYWARN;$MYCRIT"
else
	echo "UNKNOWN - got empty string (femon plugin did not answer correctly)"
	EX=$NAG_UNKNOWN
fi
exit $EX

