#!/usr/bin/perl -w

use strict;
use Getopt::Long;

my $verbose=0;
my $help;
my $hostname;
my $services;
my $initdir = '/etc/init.d';
my $debug;

my $TIMEOUT = 10;

GetOptions("help" => \$help,
           "host:s" => \$hostname,
           "services|service|s:s" => \$services,
           "initd|i:s" => \$initdir,
           "debug" => \$debug,
           "verbose|v+" => \$verbose );

my %ERRORS=(OK=>0,
            WARNING=>1,
            CRITICAL=>2,
            UNKNOWN=>3,
            DEPENDENT=>4);

if ( ! defined $services ) {
    print "UNKNOWN: missing argument service name (--service)\n";
    exit $ERRORS{"UNKNOWN"};
}

# Just in case of problems, let's not hang Nagios
$SIG{'ALRM'} = sub {
     print ("ERROR: No response from $hostname (alarm timeout)\n");
     exit $ERRORS{"UNKNOWN"};
};

alarm($TIMEOUT);

my ($result, $msg) = &check_services($services, $initdir);

alarm(0);

print "$msg\n";
exit($result);



sub check_services {
    my %status;

    foreach my $servicename ( split(/,/, $_[0]) ) {
        ($verbose > 1) and print "Checking service $servicename\n";

        my $res;
        if ( -f "$initdir/$servicename" &&
             -x "$initdir/$servicename" ) {
            my $cmd = "$initdir/$servicename status > /dev/null 2>&1";
            system($cmd);
            my $status = $? >> 8;
            
            if ( $status == 0 ) {
                $res = "OK";
            }
            elsif ( $status == 3 ) {
                $res = "WARNING";
            }
            elsif ( $status == 1 || $status == 2 ) {
                $res = "CRITICAL";
            }
            else {
                $res = "UNKNOWN";
            }
        }
        else {
            # script is not found or not executable -> status UNKNOWN
            $res = 'UNKNOWN';
        }
        $status{$res} .= "$servicename ";
        $debug and print STDERR "$servicename: $res\n";

    }

    my $retval = $ERRORS{'UNKNOWN'};
    my $msg = '';
    foreach my $res ('OK', 'UNKNOWN', 'WARNING', 'CRITICAL') {
        if ( $status{$res} ) {
            $retval = $ERRORS{$res};
            chomp $status{$res};
            $status{$res} =~ tr![ ]!,!;
            $status{$res} =~ s!,$!!g;
            $msg = "$res: $status{$res};  " . $msg;
        }
    }
    $msg ||= 'No services found';

    return ($retval, $msg);
}


