#!/usr/bin/perl

#
# gaea walters
# with some help from al on exit states
# and some help from ezra getting started
# 12.13.04
# nag1-mx
# script to check commands/services/hosts/nagios.cfg and exit with  
# critical/2 if any have been checked out longer than 60 minutes
#

# use the Rcs library to enable working with RCS files/system
use Rcs;
use lib "/usr/local/nagios/libexec";
use utils qw(%ERRORS &print_revision &support &usage);

# variables here
# time for establishing length of file checkout
$now = time();
# location of configuration files for Rcs library functions
$cfgpath = "/usr/local/nagios/etc/";
# location of RCS directory for Rcs library functions
$rcsdir = "/usr/local/nagios/etc/RCS";
# check RCS status for this list of files
@files = ("commands.cfg","services.cfg","hosts.cfg","nagios.cfg");

# loop through the files in @files and determine if they are locked; if
# a file is locked, figure out how long it's been locked; if a file has
# been locked for more than 60 minutes, exit in state critical/2 with 
# more information, including username of file locker and length of
# checkout; otherwise, exit ok/0

foreach $file (@files)
{

# set up objects for Rcs library
$cfg=Rcs->new;
$cfg->rcsdir($rcsdir);
$cfg->workdir($cfgpath);
$cfg->file($file);

$locker = $cfg->lock;

# begin checking file satus
if($locker) 
{
	# caluclate time file has been locked
        $cfg_mod_time=(stat "$cfgpath/$file")[9];
        $cfg_time_since = (($now-$cfg_mod_time)/60);
        $cfg_time_round = sprintf("%.2f",$cfg_time_since);

	# check and report locker/lock time if locked more than 60
	# minutes, exiting with state critical/2

 	if ($cfg_time_round > 60) 
	{
		print "$file is locked by $locker and was last";
		print "modified $cfg_time_round minutes ago.";
		exit $ERRORS{'CRITICAL'} 
	} #end if2

} #end if1

} #end foreach

# in all other cases (if an exit has not occurred yet) exit with state ok/0
print "Nagios config files are okay.";
exit $ERRORS{'OK'};
