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

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 multiple tcp services.
Options:
    -H <hostname> -P <portnumber> [--verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

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

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

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

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

    if (! -f $check_tcp) {
        print "Cannot find check_tcp at $check_tcp\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 $port = $options{"opt_P"};

    if ((!$port) || ($port eq "")) {
        print "\nPort number not specified.\n";
        &print_usage();
        return $ERRORS{'OK'};
    }

    my @ports = split(",", $port);

    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);

    foreach my $port (@ports) {
        my $com_output = `$check_tcp -H $host -p $port`;
        $status  = $? >> 8;
        chomp $com_output;
        $com_output =~ s/\|/: /g;

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

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

    exit $progstatus;
}

