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

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 ups connections on local host.
Options:
    [--verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

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

    print "csl_ups.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 $status = "OK";
    my $output;

    my $tmpdir = "/tmp/ups";
    my $filename = "tty";

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

    foreach my $file (sort @TMPFILES) {
        my $modification = int((-M "$tmpdir/$file") * 24 * 60);
        print "File $file has modification time of $modification minutes ago\n" if $options{verbose};

        if ($modification > 30) {
            $status = "CRITICAL";
            $output .= "$tmpdir/$file hasn't been updated in $modification minutes! ";
        } else {
            open(UPSFILE, "$tmpdir/$file") or die "Could not open $tmpdir/$file: $!\n";
            my @file_data=<UPSFILE>;
            my ($level,$error) = split(/:/,$file_data[5]);
            chomp($error);

            print "File $file has status $level and error string $error\n" if $options{"verbose"};

            if ($level eq "CRITICAL") {
                $status = "CRITICAL";
                $output .= $error;
            } elsif ($level eq "WARNING") {
                $status = "WARNING" if ($status eq "OK");
                $output .= $error;
            } elsif ($level ne "OK") {
                $status = "UNKNOWN" if ($status eq "OK");
                $output .= "$file reporting unknown error";
            }

            close(UPSFILE);
        }
    }

    ($output) || ($output = "no errors");

    print "$status: $output\n";

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

    return $ERRORS{$status};
}

