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

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 usage () {
    my $print = shift;
    print $print;
    print_usage();
}

sub print_usage () {

    print "
Usage:  Check httpd service.
Options:
    -H <hostname> -i <ips/hosts> --verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

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

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

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

    my $bindir = "/s/nagios/libexec";
    my $check_http = "$bindir/check_http";

    if (! -f $check_http) {
        print "Cannot find check_http at $check_http\n";
        return $ERRORS{'UNKNOWN'}
    }

    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'};
    }

    my %revERRORS;
    foreach my $error (sort keys(%ERRORS)) {
        $revERRORS{$ERRORS{$error}} = $error;
    }

    my $output = "";
    my $progstatus = $ERRORS{'OK'};
    my $status;

    $SIG{'ALRM'} = sub {
        print "CRITICAL: Checks not responding: $output\n";
        exit $ERRORS{'CRITICAL'};
    };
    alarm($TIMEOUT-1);

    my @CHECKS = ($host);
    @CHECKS = split (",", $options{opt_i}) if ($options{opt_i});
        
    foreach my $check (@CHECKS) {
        my $com_output = `$check_http -H $check -u /status/`;
        $status  = $? >> 8;

        chomp $com_output;
        $com_output =~ s/\n/ - /g;

        my $spacer = " # ";

        if ($options{opt_i}) {
            $spacer = " <BR> ";
            $com_output = "$check: $com_output";
        }

        if ($status > $progstatus) {
            $progstatus = $status;
            $output = $revERRORS{$status} . ": $com_output$spacer" . $output;
        } else {
            $output .= $revERRORS{$status} . ": $com_output$spacer";
        }
    }

    $output =~ s/ (<BR>|#) $//;

    # nagios perf log can no longer handle the '\' char - probably something
    # to do with the printf - don't care right now.
    $output =~ s/\\//g;
    $output =~ s/\|//g;

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

    exit $progstatus;
}

