# -*- perl -*-
#
# $Revision: 1.3 $
package afs_snapshot;

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;

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

sub print_usage () {

    print "
Usage:  Check afsd service.
Options:
    -H <hostname> -D <directory> -t <time> -i <index time> [--verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

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

    print "afs_snapshot.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 $host = $options{"opt_H"};

    if ((!$host) || ($host eq "")) {
        print "\nHost name not specified.\n";
        &print_usage();
        return $ERRORS{'OK'};
    }

    $host =~ s/\.cs\.wisc\.edu//;
    $host =~ s/\.stat\.wisc\.edu//;

    my $directory = $options{"opt_D"};
    ($directory) || ($directory = "/afs/.cs/common/afs/status");

    my $time = $options{"opt_t"};
    ($time) || ($time = 60);

    my $indextime = $options{"opt_i"};
    ($indextime) || ($indextime = 12);

    my $output = "snapshot and index complete";
    my $status = "OK";

    # SNAPSHOT
    if (-f "$directory/snapshot-$host-working") {
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = localtime(time);
        if ( ($min + ($hour * 60)) > $time ) {
            $status = "CRITICAL";
            $output = "$directory/snapshot-$host-working still exists; ";
        } else {
            $output = "$directory/snapshot-$host-working exists, but within grace period; ";
        }
    } elsif (! -f "$directory/snapshot-$host-done") {
        $status = "WARNING";
        $output = "snapshot not present: no file $directory/snapshot-$host-done; ";
    } else {
        $output = "snapshot complete; ";
    }

    # INDEX
    if (-f "$directory/index-$host-working") {
        my $modtime = (-M "$directory/index-$host-working") * 24;
        if ( $modtime > $indextime ) {
            $status = "CRITICAL";
            $output .= "$directory/index-$host-working still exists";
        } else {
            $output .= "$directory/index-$host-working exists, but within grace period";
        }
    } elsif (! -f "$directory/index-$host-done") {
        $status = "WARNING" if ($status = "OK");
        $output .= "index not present: no file $directory/index-$host-done";
    } else {
        $output .= "index complete";
    }

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

    exit $ERRORS{$status};
}

