use warnings;

#Nagios Return Codes
$ng_ok = 0;
$ng_warn = 1;
$ng_crit = 2;
$ng_err = 3;

#Input
unless ($#ARGV == 0){
   print "Input must be: 'list of essential services'\n";
   exit $ng_err;
}

$essential = shift @ARGV;
@essential = split " ", $essential;

@servicelist = `sc query`;
@notrunning = ();
$runningservices = '';

foreach $service(@servicelist){
   chomp $service;
   if ($service =~ /SERVICE_NAME/){
      (undef, $servicename) = split /: /, $service;
   }
   if ($service =~ /STATE/){
      if ($service =~ /RUNNING/){
         $runningservices .= " $servicename";
      }
   }
}

foreach (@essential){
   if ($runningservices !~ /$_/i){
      push @notrunning, $_;
   }
}

if (@notrunning){
   $notrunning = $#notrunning + 1;
   print "Critical: $notrunning essential services not running\n";
   print join(' ', @notrunning);
   print "\n";
   exit $ng_crit;
} else {
   print "OK: All essential services appear to be running\n";
   exit $ng_ok;
}
