#!/usr/bin/perl -w

# Version:      02
# Date:         Nov 3, 2021
# Author:       ivan.stetka@live.com
# Summary:      This is a Nagios NCPA plugin for check count files/directories in directory
#
# On host side copy plugin to directory '/usr/local/ncpa/plugins/'
#
# Nagios example:
# ./check_ncpa.py -H '<host IP>' -t '<your token>' -M 'plugins/check_file_count.pl' -a "-D '/var/tmp/'' -w 100 -c 200 -f"
#

use strict;
use Getopt::Long qw(:config no_ignore_case bundling);

my %STATES = (
    OK          => 0,
    WARNING     => 1,
    CRITICAL    => 2,
    UNKNOWN     => 3
);

my $directory = undef;
my $warn = undef;
my $crit = undef;
my $fileType = 0;
my $help = 0;
my $commandType = '';
my $directoryText = '';
my $fileDirectoryCount = 0;

GetOptions(
    'D|directory:s'     => \$directory,
    'w|warning:n'       => \$warn,
    'c|critical:n'      => \$crit,
    'f|file'            => \$fileType,
    'h|help'            => \$help
);

if ($help) {
    help();
    exit($STATES{OK});
}

if (!defined $warn || !defined $crit || !defined $directory) {
    print "UNKNOWN: Missing some required parameter (warning, critical or directory').\n";
    help();
    exit($STATES{UNKNOWN});
}

if ($crit <= 0 || $warn <= 0) {
    print "UNKNOWN: Incorrect warning: '$warn' or critical: '$crit' threshold.\n";
    help();
    exit($STATES{UNKNOWN});
}

unless (-d $directory) {
    print "Directory '$directory' doesn't exist!\n";
    exit($STATES{CRITICAL});
    }

if ($fileType) {
    $commandType = '-type f ';
}

open BC1, "find $directory $commandType 2> /dev/null | wc -l |";
$fileDirectoryCount = <BC1>;
close BC1;
$fileDirectoryCount =~ s/\n//;

if (!$fileType) {
    $fileDirectoryCount = $fileDirectoryCount -1;
    $directoryText = ' and directories';
}

if ($fileDirectoryCount !~ /^\d+$/ ) {
    print "CRITICAL: Linux command error (Count): $fileDirectoryCount\n";
    exit($STATES{CRITICAL});
}

my $text = "Directory '$directory' contains $fileDirectoryCount files$directoryText.\n|'Count'=$fileDirectoryCount;$warn;$crit;\n";

if ($fileDirectoryCount >= $crit ){
    print "CRITICAL: $text";
    exit($STATES{CRITICAL});
} elsif ($fileDirectoryCount >= $warn ){
    print "WARNING: $text";
    exit($STATES{WARNING});
} else {
    print "OK: $text";
    exit($STATES{OK});
}

# # # SUBROUTINES # # #

#   Help subroutine
sub help {
    print <<HELP;
H E L P:

This is a nagios NCPA plugin for check linux files and directories count in directory,

-D, --directory         # full path to direcory
                        # example direcory: '/var/tmp/'
-w, --warning           # warning threshold of maximum count item (files/directories) in the directory
-c, --critical          # critical threshold of maximum count item (files/directories) in the directory
-f, --file              # count only files in directory
-h, --help              # print this help

HELP
}
