# -*- perl -*-
#
# $Revision: 1.2 $
package cricket_logs;

require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&print_usage &print_version &service_test);
use lib $main::runtimedir;
use csl_utils qw($TIMEOUT %ERRORS);

use strict;

use File::Copy;
use Date::Parse;

use CSL::What;
use What::Data;

use CSL::Nagios;
use Nagios::Cricket;

sub print_usage ();
sub print_version ();
sub service_test (%);

sub print_usage () {

    print "
Usage:  Check cricket logs.
Options:
    [--verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

sub print_version () {
    my $version = '$Revision: 1.2 $';
    $version =~ s/^\$Revision: //;
    $version =~ s/ \$\s*$//;

    print "cricket_logs.pm - $version\n";
    return $ERRORS{'OK'};
}

sub service_test (%) {
    my %options = @_;

    if ($options{"verbose"}) {
        foreach my $opt (sort keys(%options)) {
            if ($options{$opt}) {
                print "$opt - $options{$opt}\n";
            }
        }
    }

    my @ignorefiles;
    if ($options{"opt_i"}) {
        @ignorefiles = split(",", $options{"opt_i"});
    }

    my $status = "OK";
    my $output;

    my %months = (
        Jan => 1,
        Feb => 2,
        Mar => 3,
        Apr => 4,
        May => 5,
        Jun => 6,
        Jul => 7,
        Aug => 8,
        Sep => 9,
        Oct => 10,
        Nov => 11,
        Dec => 12,
    );

    my $rootlogdir = "/p/lab/cricket-logs";
    my $errordir = "$rootlogdir/errors";
    my %errorfiles;
    my %errors;

    # Start with a base of What::Data
    my $Data = new What::Data;

    foreach my $directory ("collect-subtrees", "localcollector") {
        my $logdir = "$rootlogdir/$directory";

        opendir(DIR, $logdir) || die "Must have valid logdir!\nCan't opendir $logdir: $!";
        my @LOGFILES = grep { !/^\./ } readdir(DIR); # Get all non-dot files
        closedir DIR;

        my %roots;
        FILE: foreach my $file (sort @LOGFILES) {

            # ignore the file if it's older than a day.
            my $modification = -M "$logdir/$file";
            $modification = ( int ($modification * 10) / 10 );
            next FILE if ($modification > 1);

            # don't die - files being moved around all the time.
            open (IN, "$logdir/$file") or next FILE;

            my $date;
            (my $root = $file) =~ s/\.\d+$//;

            foreach my $ignore (@ignorefiles) {
                next FILE if ($ignore eq $root);
            }

            # if file is something like dns-test-<setup host>, don't warn.
            unless ($roots{$root}) {
                $roots{$root} = Nagios::Cricket->checkFileName($root, $Data);
                ($roots{$root}) || ($roots{$root} = "OK");
            }
            next FILE if ($roots{$root} eq "Setup");

            LINE: while (my $line = <IN>) {
                # date
                # current: 06-Oct-2005 10:49:14
                # new: _2005-10-06_11:15
                unless ($date) {
                    $line =~ /^\[(\d\d)-(\w+)-(\d\d\d\d) (\d\d)\:(\d\d)\:\d\d.\]/;
                    $date = "$3-" . $months{$2} . "-$1_$4:$5";
                }

                next FILE if (-f "$errordir/$root/$date");

                my $error = Nagios::Cricket->errorLine($line, $Data);
                next LINE unless $error;

                (my $printerror = $error) =~ s/^\[(\d\d)-(\w+)-(\d\d\d\d) (\d\d)\:(\d\d)\:\d\d.\]//;
                chomp ($printerror);
                $errors{$root} = "{$printerror}";

                $errorfiles{$root}=$logdir;

                if ($status ne "WARNING") {
                    $status = "WARNING";
                    print "status WARNING because of: $line" if $options{"verbose"};
                    $output = "error in files ";
                }

                (-d "$errordir/$root") || (mkdir "$errordir/$root") or die "no directory $errordir/$root: $!\n";

                print "cp $logdir/$file $errordir/$root/$date\n" if $options{"verbose"};

                copy ( "$logdir/$file", "$errordir/$root/$date" ) or
                                die "Could not copy $logdir/$file: $!\n";

                next FILE;

            }
            close IN;
        }
    }

    opendir(DIR, $errordir) || die "Can't opendir $errordir: $!\n";
    my @ROOTDIRS = grep { !/^\./ } readdir(DIR); # Get all non-dot files
    closedir DIR;

    ROOT: foreach my $root (@ROOTDIRS) {
        next ROOT unless (-d "$errordir/$root");
        opendir(DIR, "$errordir/$root") || die "Can't opendir $errordir/$root: $!\n";
        my @LOGFILES = grep { !/^\./ } readdir(DIR); # Get all non-dot files
        closedir DIR;

        FILE: foreach my $file (sort @LOGFILES) {
            $file =~ /(\d\d\d\d)-(\d+)-(\d+)_(\d\d\:\d\d)/;
            if (((time() - str2time("$2/$3/$1 $4")) / 60 / 60 / 24) > 7) {
                print "rm $errordir/$root/$file\n" if $options{"verbose"};
                unlink("$errordir/$root/$file") or die "Couldn't remove $errordir/$root/$file: !$\n";
            }
        }
    }

    my $lastroot;
    foreach my $key (sort {"$errorfiles{$a}/$a"  cmp "$errorfiles{$b}/$b"} keys %errorfiles) {
        if ($errorfiles{$key} ne $lastroot) {
            chop $output;
            $lastroot = $errorfiles{$key};
            $output .= "<br>$lastroot/ ";
        }
        #$output .= "<br>./$key $errors{$key} ";
        $errors{$key} =~ /^(.{0,80})/;
        $output .= "<br>./$key $1";
    }

    ($output) || ($output = "All cricket logs look fine.");

    print "$status: $output\n";

    print "Exit status: $status\n" if $options{"verbose"};

    return $ERRORS{$status};
}

