#!/bin/sh
#
# $Id: check_fd 333 2014-04-01 14:02:13Z phil $
#
# checks open ip file descriptors in general or by a given pid
# returns nagios compatible status and perfdata.
#
# Author: Philippe Kueck <projects at unixadm dot org>
#

warn=1500
crit=2000
host=localhost

nagexit() {
	declare -a nexitc=('OK' 'WARNING' 'CRITICAL' 'UNKNOWN')
	echo "${nexitc[$1]} - $2 file descriptors|'descriptors'=$2;$warn;$crit;0"
	exit $1

}

while getopts ":H:w:c:p:" opt; do
	case $opt in
		H);; 
		w) warn=$OPTARG;;
		c) crit=$OPTARG;;
		p) pid=$OPTARG;;
		*) echo "usage: $0 [-w <warn>] [-c <crit>] [-p <pid>]"
		   exit 3;;
	esac
done

if [ -n "${pid}" ]; then
	if ! [[ $pid =~ ^[0-9]+$ ]]; then
		[ -r "${pid}" ] || nagexit 3 0
		pid=$(cat $pid)
		[[ $pid =~ ^[0-9]+$ ]] || nagexit 3 0
	fi
	fds=$(/usr/sbin/lsof -n -P -a -i -p ${pid} | wc -l)
else
	fds=$(/usr/sbin/lsof -n -P -i | wc -l)
fi

[ $fds -ge $crit ] && nagexit 2 $fds
[ $fds -ge $warn ] && nagexit 1 $fds
nagexit 0 $fds
