#!/usr/bin/perl

$|++;

if ( -r "/etc/maintenance" ) {
    exit 0;
}

$VERBOSE = 0;

if ($ARGV[0] eq '-v') {
    $VERBOSE = 1;
}

#  Process name to find in ps    |  Service control script to call
#  output (ps auxwww)            |  to restart the script if the
#                                |  process is not found in ps

my %services = qw(
    /usr/sbin/httpd                 httpd
    mysqld                          mysqld
    named                           named
    /usr/sbin/sshd                  sshd
    sendmail                        sendmail
    \s+crond                        crond
);

for my $service (keys %services) {
    print "Checking $service: " if $VERBOSE;
    if (! check_service($service)) {
        print "NOT OK\n" if $VERBOSE;
        restartit($service, $services{$service});
    } else {
        print "OK\n" if $VERBOSE;
    }
    sleep(1);
}

exit 0;

sub restartit {

    my $bin  = shift;
    my $init = shift;

    if (! check_service($bin)) {
        print "o    Attempting to restart $init: ";
        if (system("/etc/rc.d/init.d/$init restart 2>&1")) {
            print "failed ($!)\n";
        } else {
            print "success\n";
        }
    }

    sleep(10);

}

sub check_service {

    my $svc = shift;

    local(*PS);
    local($_);
  
    open(PS,"/bin/ps auxwww |") || die "Can't ps: $!\n";

    my $found = 0;

    while(<PS>) {
        if (/$svc/) {
            $found = 1;
            last;
        }
    }

    close(PS);

    return $found;

}

sub logger {
    my $msg = shift;
    print scalar localtime(time()), ": $msg\n";
}