#!/usr/bin/ksh
#
# Nagios Plugin for checking number of files in a certain directory.
#
# Description: Checking number of files in a given directory.
#
# Author     : Thomas Ebeling
# Version    : 1.0
# Date       : 2007-05-29
# 
#

LANG=C
export LANG

REVISION='$Revision: 1.3 $ '

# where we are started
WHERE=`dirname $0`

# setting default exit values
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

# import exit values from utils.sh if we found one
if   [ -f ${WHERE}/utils.sh ] ; then
    . ${WHERE}/utils.sh
elif [ -f ${WHERE}/../utils.sh ] ; then
    . ${WHERE}/../utils.sh
fi

usage() {
    echo "Usage: $0 [-w <number of files>] [-c <number of files>] [-m <file mask>] [<path>]"
    echo "Revision: $REVISION"
    echo 
    echo "Determines the number of files in a given directory, including sub-directories."
    echo 
    echo "Warning and critical thresholds are optional. If no path is supplied, "
    echo "the current working directory is selected."
    exit $STATE_UNKNOWN
}

warning=''
critical=''
mask=''
check_dir=`pwd`

while [ "$1" != "" ]; do
	case $1 in
	-w)
		shift
		warning=`echo $1 | tr -dc '[:digit:]'`
		;;
	-c)
		shift
		critical=`echo $1 | tr -dc '[:digit:]'`
		;;
	-m)
		shift
		mask=`echo $1`
		;;
	-*)
		usage
		;;
	*)
		check_dir=$1
	esac
	shift
done

if [[ $critical != "" && $critical -le 0 ]] ; then
	echo "Critical must be a positive integer."
	exit $STATE_UNKNOWN
fi

if [[ $warning != "" && $warning -le 0 ]] ; then
	echo "Critical must be a positive integer."
	exit $STATE_UNKNOWN
fi

if [[ $critical != "" && "$warning" != "" && $critical -le $warning ]]; then
	echo "Warning must be less than critical value."
	exit $STATE_UNKNOWN
fi

if [[ $mask != "" ]]; then
	count=`find $check_dir -follow -type f -name "$mask" 2>/dev/null | wc -l | tr -d '[:space:]'`
else
	count=`find $check_dir -follow -type f 2>/dev/null | wc -l | tr -d '[:space:]'`
fi
rc=$STATE_OK

if [[ $critical != "" && $count -ge $critical ]]; then
	printf "CRITICAL - "
	rc=$STATE_CRITICAL
elif [[ $warning != "" && $count -ge $warning ]]; then
	printf "WARNING - "
	rc=$STATE_WARNING
else
	printf  "OK - "
fi
echo "$count files found.|count=$count"
exit $rc

