#!/usr/bin/perl -w
=head1 NAME
check_filetest - Check various file properties
=head1 AUTHOR
Shadhin Rahman <sr2690@columbia.edu> 
=head1 SYNOPSYS
This particular plugin written from filetest survivor checks.
=head1 REQUIRES
Perl5.87, strict, Nagios::Plugin
=head1 EXPORTS
Nothing
=head1 DESCRIPTION
Checks file properties
=cut

use warnings;
use strict;
use File::Basename;
use Nagios::Plugin;

my( $usagemsg ) = <<USAGE;
Usage: %s [ -v|--verbose ]  [-O|--op] [-G|--grep] [-s|--showline] [-w|--timeewarn] [-c|--timecrit]
[ -m|--timemax=<threshold> ] [ -w|--countwarn=<threshold> ] [-c|--countcrit=<threshold>] [-n|--name]
USAGE
my( $blurb ) = <<BLURB;
checks file properties
BLURB
my( $license ) = <<LICENSE;
Copyright (c) 2008 - 2009
The Trustees of Columbia University in the City of New York# Academic Information Systems
License restrictions apply.
LICENSE

Nagios::Plugin->new(
    usage => "Usage: %s [ -v|--verbose ] [-G|--grep] [-s|--showline] [-w|--timeewarn] [-c|--timecrit]"
    . "[ -m|--timemax=<threshold> ] [ -w|--countwarn=<threshold> ] [-c|--countcrit=<threshold>] [-n|--name],"
);
my( $plugin ) = Nagios::Plugin->new(
    shortname	=> 'filetest',
    usage	=> $usagemsg,
    version	=> '0.2',
    blurb	=> $blurb,
    license	=> $license,
    plugin      => basename $0,
    timeout	=> 20,
);
=head2 Plugin Metadata

Metadata is documented in L<Nagios::Plugin> and L<Nagios::Plugin::Getopt>.

=cut

$plugin->add_arg(
    spec           => 'grep|G=s',
    help           => "string or regular expression",
    label          => 'grep',
    default        => 'error',
    required       => 1,
);
$plugin->add_arg(
    spec           => 'showline|s=s',
    help           => "show what line we found the problem",
    label          => 'showline',
    default        => 'no',
    required       => 0,
);
$plugin->add_arg(
    spec           => 'countcrit|c=i',
    help           => "how many instances of grep string should be critical",
    label          => 'Time maximum',
    required       => 0,
);
$plugin->add_arg(
    spec           => 'timemax|m=i',
    help           => "how many minutes back we should look",
    label          => 'Time maximum',
    required       => 0,
);
$plugin->add_arg(
    spec           => 'match|M=i',
    help           => "oldest or newest match 0 mean old 1 mean new",
    label          => 'matchone',
    required       => 0,
);
$plugin->add_arg(
    spec           => 'name|n=s',
    help           => ["Name of the file"],
    label          => ['filename'],
    default        => '/var/log/message',
    required       => 1,
);
$plugin->add_arg(
    spec           => 'date|d=s',
    help           => ["log format type, either epo or reg"],
    label          => 'date',
    default        => 'reg',
    required       => 0,
);
$plugin->getopts;
my ( $opts ) =$plugin->opts;

# Convert times to seconds.  If not set, these times will end up as 0.
my $countcrit = $opts->get("countcrit") || 1;
my $timemax = $opts->get("timemax") || 10; 
my $showline = $opts->get("showline");
my $xgrep = $opts->get("grep");
my $matchtime = $opts->get("match") || 0;
my @name = $opts->get("name");
my $dateformat = $opts->get("date");
my $returnstring='';
my $status=0;
my $r = FiletestCheck();

if ($status == 0){
    $plugin->add_perfdata(
        label => "filename",
        value =>'1',
    );
    $plugin->nagios_exit (OK, "$returnstring");
}
elsif ($status == 1){
    $plugin->add_perfdata(
        label => "filename",
        value =>'0',
    );
    $plugin->nagios_exit (WARNING, "$returnstring");
}
elsif ($status == 2){
    $plugin->add_perfdata(
        label => "filename",
        value =>'0',
    );
    $plugin->nagios_exit (CRITICAL, "$returnstring");
}
else{
    $plugin->add_perfdata(
        label => "filename",
        value =>'0',
    );
    $plugin->nagios_exit (UNKNOWN, "$returnstring");
}


sub FiletestCheck {
    foreach my $opfile (@name) {
        open(INFILE, "<$ opfile") or die "Could not open $opfile\n";
        my $found = 0;
        my $lineno = 0;
        my @matchlines;
        while ( <INFILE> ) {
            $lineno++;
            chomp;
            if ($_=~ qr/$xgrep/mo){
                my $bool_value = KeepLine($_);
                if ( $bool_value eq '1') { 
                    $found++;
                    $returnstring= "We have found $xgrep in $opfile";
                    push (@matchlines, $lineno);
                    if  ( ($showline eq 'yes')  &&  (define ( $showline )) ){
                        $returnstring= $returnstring . " " . scalar(@matchlines) . " times";
                    }
                }
            }
        } #end of while <INFILE>
        close INFILE;

        if ($found > 0 ) {
            if ( scalar ( @matchlines) >= $countcrit ) {
                $status = 2;
            }
            else {
                $status=0;
            }
        }

    }
} 

sub KeepLine {
    my ($compare_line)=@_;
    my $bool_find = 0;
    if ($dateformat eq 'reg') {
        my ($mons, $days, $times, @actul_string)=split(' ', $compare_line);
        my ($hrs, $mins, $secs)= split(':', $times);
        my ( $cur_sec,$cur_min,$cur_hour,$cur_mday,$cur_mon,$cur_year,$cur_wday,$cur_yday,$cur_isdst ) = localtime();
        if ( ($days -$cur_mday <1 ) && ($hrs - $cur_hour <1 ) && ( $cur_min - $mins < $timemax ) ) {
            $bool_find=1;    
        }
    }

    elsif ( $dateformat eq 'epo') {
        my ($epoch_time, @actual_string) = split ( ' ', $compare_line);
        my $changed_time = (scalar($epoch_time));
        my ($date, $mon, $days, $times, $year) = (' ', $changed_time);
        my ($hrs, $mins, $secs)= split(':', $times);
        my ( $cur_sec,$cur_min,$cur_hour,$cur_mday,$cur_mon,$cur_year,$cur_wday,$cur_yday,$cur_isdst ) = localtime();
        if ( ($days -$cur_mday <1 ) && ($hrs - $cur_hour <1 ) && ( $cur_min - $mins < $timemax ) ) {
            $bool_find=1;
        }
    }
    else {
        $plugin->nagios_die ("date format is not correct", UNKNOWN);
    }
    return $bool_find;
}
