#!/usr/bin/perl -wt

use strict;

use Getopt::Long;
use lib "/usr/lib64/nagios/plugins";
use utils qw (%ERRORS &print_revision &support);

my $PROGNAME="check_num_files";

my ($opt_c, $opt_d, $opt_h, $opt_w, $opt_V);

Getopt::Long::Configure('bundling');
GetOptions ( "V"   => \$opt_V, "version"         => \$opt_V,
             "d=s" => \$opt_d, "directory"       => \$opt_d,
             "h"   => \$opt_h, "help"            => \$opt_h,
             "w=f" => \$opt_w, "warning-count"   => \$opt_w,
             "c=f" => \$opt_c, "critical-count"  => \$opt_c);

sub show_help
{
  print "\nUsage:\n";
  print " $PROGNAME: -d <directory path> [-w <warning threshold>] [-c <critical threshold>]\n";
  print " $PROGNAME: [-h | --help]\n";
  print " $PROGNAME: [-V | --version]\n\n";
}

if ( $opt_V )
{
  print_revision($PROGNAME, '$Id: l,v 1.3 2005/12/15 15:17:49 tonvoon Exp $');
  exit $ERRORS{'OK'};
}

if ( $opt_h )
{
  show_help();
  exit $ERRORS{'OK'};
}

if ( ! $opt_d )
{
  print "ERROR: Directory has not been specified\n";
  exit $ERRORS{'UNKNOWN'};
}

if ( ! -d $opt_d )
{
  print "ERROR: Directory not found - $opt_d!\n";
  exit $ERRORS{'CRITICAL'};
}

#
# Define some constants if not defined already
###
$opt_w  = 0 unless defined ($opt_w);
$opt_c  = 5 unless defined ($opt_c);
my $result  = "OK";
my $count   = 0;

opendir (DIR, $opt_d);
while ( $_ = readdir(DIR) )
{
  next if /^\.$/ or /^\.\.$/;
  $count++;
}
closedir(DIR);

if ( $count > $opt_c )
{
  $result = "CRITICAL";
}
elsif ( $count > $opt_w )
{
  $result = "WARNING";
}

print "PATH $result: \"$opt_d\" contains $count file" . (($count == 1 ) ? "" : "s") . "\n";
exit $ERRORS{$result};

