#!/bin/sh
# 
# Plugin to monitor the number of open files in the system.
#
# Parameters:
# 	
# 	config   (required)
# 	autoconf (optional - used by munin-config)
#
# Magic markers (Used by munin-config and some installation scripts.
# Optional):
#
#%# family=contrib
#%# capabilities=autoconf


PROC=`basename $0 | sed 's/^files_//g'`
TMPFILE="@@PLUGSTATE@@/munin-files_${PROC}.state"

if [ "$1" = "autoconf" ]; then
	if [ -x /usr/sbin/lsof ]; then
		echo yes
		exit 0
	else
		echo no
		exit 1
	fi
fi

if [ "$1" = "config" ]; then

	echo 'graph_title slapd open files usage'
	echo 'graph_args --base 1000 -l 0'
	echo 'graph_vlabel number of files'
	echo 'graph_category system'
	echo 'cnt.label Slapd proc count'
	echo 'avg.label avg all slapd proc'
	echo 'max.label max slapd files'
	echo hei | awk  '{printf "max.warning %d\nmax.critical %d\n",900,960}'
	exit 0
fi

if [ "$1" = "collect" ]; then
  for ALL in $(pgrep -u root $PROC) ; do 
    lsof -p $ALL | wc -l 
  done | sort -n | \
    awk '{ C=C+1 ;  S=S + $1 ; M=$1 } END { printf "cnt.value %d\navg.value %d\nmax.value %d\n", C, S/C, M} ' 
else
  [ -f $TMPFILE ] && cat $TMPFILE
  echo "/etc/munin/node.d/slapd_files collect > $TMPFILE" | at +4min 2>/dev/null
fi
