#!/bin/sh
# written by Steve Murphy, with inspiration from Dmitry Vayntrub's check_uptime.sh
#
# The plugin shows the number of open files by asterisk
# and allows you to set warn/crit values in case asterisk
# 'leaks' open file descriptors.
#
#######################################################################
VERSION="check_asterisk_openfiles v1.00"

# Exit-Codes:
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

usage()
{
cat << EOF
usage: $0 [-c OPTION]|[-w OPTION] [-C OPTION]|[-W OPTION] [ -V ]

This script checks how many open files that asterisk has requested and optionally verifies if that 
number is below MINIMUM or above MAXIMUM treshholds

OPTIONS:
   -h   Help
   -c   CRITICAL MIN uptime (minutes)
   -w   WARNING  MIN uptime (minutes)
   -C   CRITICAL MAX uptime (minutes)
   -W   WARNING  MAX uptime (minutes)
   -V   Version
EOF
}

while getopts c:w:C:W:Vv OPTION
do
     case $OPTION in
	c)
	   MIN_CRITICAL=`echo $OPTARG | grep -v "^-"`
	   [ ! "$?" = 0 ] && echo "Error: missing or illegal option value" && \
	   exit $STATE_UNKNOWN
	   ;;
	w)
	   MIN_WARNING=`echo $OPTARG | grep -v "^-"`
	   [ ! "$?" = 0 ] && echo "Error: missing or illegal option value" && \
	   exit $STATE_UNKNOWN
	   ;;
	C)
	   MAX_CRITICAL=`echo $OPTARG | grep -v "^-"`
	   [ ! "$?" = 0 ] && echo "Error: missing or illegal option value" && \
	   exit $STATE_UNKNOWN
	   ;;
	W)
	   MAX_WARNING=`echo $OPTARG | grep -v "^-"`
	   [ ! "$?" = 0 ] && echo "Error: missing or illegal option value" && \
	   exit $STATE_UNKNOWN
	  ;;
	V)
	   echo $VERSION
	   exit $STATE_OK
	   ;;
	v)
	   VERBOSE=1
	   ;;
	?)
	   usage
	   exit $STATE_UNKNOWN
	   ;;
     esac
done

LSOF_REPORT=`/usr/lib/nagios/plugins/my_lsof | wc -l`
PERFDATA="|openFiles=$LSOF_REPORT"

if [ $MIN_CRITICAL ] && [ $LSOF_REPORT -lt $MIN_CRITICAL ] ; then
	echo "CRITICAL - open files ($LSOF_REPORT) less than threshold of $MIN_CRITICAL$PERFDATA"
	exit $STATE_CRITICAL

  elif [ $MIN_WARNING ] && [ $LSOF_REPORT -lt $MIN_WARNING ] ; then
	echo "WARNING - open files ($LSOF_REPORT) less than threshold of $MIN_WARNING$PERFDATA"
	exit $STATE_WARNING

  elif [ $MAX_CRITICAL ] && [ $LSOF_REPORT -gt $MAX_CRITICAL ] ; then
	echo "CRITICAL - open files ($LSOF_REPORT) greater than threshold of $MAX_CRITICAL$PERFDATA"
	exit $STATE_CRITICAL

  elif [ $MAX_WARNING ] && [ $LSOF_REPORT -gt $MAX_WARNING ] ; then
	echo "WARNING - open files ($LSOF_REPORT) greater than threshold of $MAX_WARNING$PERFDATA"
	exit $STATE_WARNING

  else
	echo "OK - Number of open files is $LSOF_REPORT$PERFDATA"
	exit $STATE_OK
fi
