#!/usr/bin/perl
use strict;
use File::Copy;

our $opmoncmd = "/usr/local/opmon/var/rw/opmon.cmd";


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

	$hostname = shift;
	$servicename = shift;

	if (!-e $opmoncmd) {
		print("CRITICAL - Impossivel acessar $opmoncmd\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,">$opmoncmd");
	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/opmon/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 - Agendamentos com problema: $critical -> $outstr\n");
		exit 2;
	}

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


main();
