#!/usr/bin/perl

use Nagios::StatusLog;
use Getopt::Std;
use vars qw($opt_c $opt_o $opt_v $opt_h);
use strict;
use warnings;

getopts('c:v:h');

if (!$opt_c || defined($opt_h)) {
  require File::Basename;
  print "Must specify location of Nagios configuration with -c option.\n" if (!$opt_c);
  die "USAGE: " . File::Basename::basename($0) . " -c <cfg_file> [ -v <cfg_version ]\n";
}

# Only tested with Nagios v2.7 (2.0)
my $version = (defined($opt_v) ? $opt_v : '2.0');

open (CONFIG, $opt_c) or die "Can't open Nagios config file: $!";

my ($status_file, $command_file) = ();
while (<CONFIG>) {
  next unless m/^(status_file|command_file)=(.+)$/;
  $status_file = $2 if ($1 eq 'status_file');
  $command_file = $2 if ($1 eq 'command_file');
}
close (CONFIG);

if (!$status_file || !$command_file) {
  die "Could not find status_file and command_file in the main Nagios config file.";
}

my $log = Nagios::StatusLog->new(
  Filename => $status_file,
  Version  => $version
);

# Get time, initialize variables
my $ts = time;
my ($hcount, $scount);

foreach my $host ($log->list_hosts()) {
  my $hchk = 0;
  foreach my $service ($log->list_services_on_host($host)) {

    # With Nagios::Object I could check for volatile services, but it is
    # way too buggy. Insteat we use a match.
#    if ($service =~ /^.+Trap$/) {
    if ($$log{'SERVICE'}{$host}{$service}{'should_be_scheduled'} == 0 &&
        $$log{'SERVICE'}{$host}{$service}{'active_checks_enabled'} == 1) {
      open (COMMAND, ">$command_file") or die "Can't open Nagios command file: $!";
      printf COMMAND "[%lu] SCHEDULE_FORCED_SVC_CHECK;%s;%s;%lu\n", $ts, $host, $service, $ts;
      close(COMMAND);
      $scount++;
      $hchk = 1;
    }
  }
  $hcount += $hchk;
}

print "Reset $scount volatile services on $hcount hosts\n";

