#!/usr/bin/perl

use strict;
use Getopt::Std;

my %opt = ();
getopts("hd:w:c:", \%opt);

my $dir = $opt{'d'};
my $w = $opt{'w'}; 
my $c = $opt{'c'};
my @files;
my $fullpath;
my $retval = 0;
my $output;
my $critfiles;
my $warnfiles;
my $files;

if( not ($w && $c && $dir) or $opt{'h'} ) {
	print "$0 v1.0 by Patrick Webster <patrick\@aushack.com>\n

This nagios plugin comes with ABSOLUTELY NO WARRANTY. You may redistribute
copies of this plugin under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.

Script based on check_filesize_dir.pl by
Copyright (c) 2006  by Christian Reiter <c.reiter\@gmx.net>

Check number of Files in a Directory 
Useful for Mailboxes, AV, mail queue and similar files.\n
Usage: ./$0 -d <DIRECTORY> -w <WARNSIZE> -c <CRITICALSIZE>

-d <DIRECTORY>     the Directory to check (example: /var/spool/mail)
-c <CRITICAL>      Critical threshold in file count (example: 100)
-w <WARNING>       Warning threshold in file count (example: 75)
-h                 displays the Help message
\n\n";
	exit 3;
};

unless( $w <= $c ) {
	print "Error: Warninglevel must not be higher than critical\n\n";
	exit 3;
};

opendir(DIR, $dir);
$files = @files = readdir(DIR);
closedir(DIR);

if( $files >= $c ) { $retval = 2; };
if( $files >= $w ) { $retval = 1 if $retval < 2;} ;

if ( $retval == 0 ) {
	print "OK: File count - " . $files . "\n";
	exit $retval;
} elsif ( $retval == 1 ) {
	print "WARNING: File count - " . $files . "\n";
	exit $retval;
} elsif ( $retval == 2 ) {
	print "CRITICAL: File count - " . $files . "\n";
	exit $retval;
};

exit $retval;