#!/usr/bin/perl
# Copyright (C) 2008, 2009  OpServices Tecnologia da Informacao
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  Author: Ricardo Jose Maraschini <ricardo.maraschini@opservices.com.br>

use strict;
use File::Copy;

our $nagioscmd = "/usr/local/nagios/var/rw/nagios.cmd";


sub schedule_check
{
	my $hostname;
	my $servicename;
	my $ts;
	my $cmdline;

	$hostname = shift;
	$servicename = shift;

	if (!-e $nagioscmd) {
		print("CRITICAL - Unable to access file $nagioscmd\n");
		exit 2;
	}


	$ts = time();
	if ($servicename ne "") {
		$cmdline = "[$ts] SCHEDULE_SVC_CHECK;$hostname;$servicename;$ts\n";
	} else {
		$cmdline = "[$ts] SCHEDULE_HOST_CHECK;$hostname;$ts\n";
	}

	open(CMD,">$nagioscmd");
	print CMD $cmdline;
	close(CMD);

}



sub main()
{
	my $savfile;
	my $newsavfile;
	my $checklimit;
	my $nextcheck;
	my $hostname;
	my $servicename;
	my $outstr;
	my $critical;

	$newsavfile = "/tmp/status.sav";
	$savfile = "/usr/local/nagios/var/status.sav";
	if (!-f $savfile) {
		print("Unable to find file $savfile, bailing out...\n");
		exit 3;
	}
	
	$checklimit = time() + (7 * 24 * 60 * 60);

	copy($savfile, $newsavfile) or die "File $savfile cannot be copied.\n";

	open(SAV,"<$newsavfile");
	$critical = 0;
	
	foreach(<SAV>) {
		if (m/^next_check=(\d+)$/) {
			if ($1 > $checklimit) {
				$critical++;

				$outstr .= "$hostname ";
				if ($servicename ne "") {
					$outstr .= "($servicename) ";
				}

				schedule_check($hostname,$servicename);

				$hostname = "";
				$servicename = "";
			}
		}
		if (m/^host_name=(.*)$/) {
			$hostname = $1;
		}
		if (m/^service_description=(.*)$/) {
			$servicename = $1;
		}
	}
	close(SAV);

	if ($critical >= 1) {
		print("CRITICAL - Problems: $critical -> $outstr\n");
		exit 2;
	}

	print("OK - Schedule seems to be fine\n");
	exit 0;
}


main();
