#!/bin/sh
#
# $Id: check_semaphores 318 2014-03-25 19:19:39Z phil $
#
# checks semaphores
# returns nagios compatible status and perfdata.
#
# Author: Philippe Kueck <projects at unixadm dot org>
#

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

}

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

if [ -z "${owner}" ]; then
	[ -n "${crit}" ] || crit=$(ipcs -l | awk '/max semaphores system wide/{print $6}')
	sem=$(ipcs -s | grep -c ^0x)
else
	[ -n "${crit}" ] || crit=$(ipcs -l | awk '/max semaphores per array/{print $6}')
	sem=$(ipcs -s | awk "{if (\$3 == \"${owner}\") {CNT++}} END{print CNT}")
fi

[ -n "${warn}" ] || warn=$(( $crit * 9 / 10))
[ $sem -ge $crit ] && nagexit 2 $sem ${owner:-total}
[ $sem -ge $warn ] && nagexit 1 $sem ${owner:-total}
nagexit 0 $sem ${owner:-total}
