#!/usr/bin/perl
#

use strict;

my %service_data = ();
my %host_data = ();
my $file="/var/log/nagios/status.dat";

open (FL, $file) or die "Could not open file $file - !";
my $block="";
my $bdata;
while (<FL>) {
	if ( !$block && /\s*(\w+)\s+{/ ) {
		$block=$1;
		$bdata={};
	}
	elsif ( $block && /\s*}/) {
		if ($block eq "host" && defined($bdata->{'host_name'})) {
			$host_data{$bdata->{'host_name'}}=$bdata;
		}
		if ($block eq "service" && defined($bdata->{'host_name'}) && defined($bdata->{'service_description'})) {
			$service_data{$bdata->{'host_name'}.'_____'.$bdata->{'service_description'}}=$bdata;
		}
		$block="";
	}
	elsif ( $block && /\s*(\w+)=(.*)/ ) {
		$bdata->{$1}=$2;
	}
}
close(FL);

my %stats=('_all_'=>{tnum=>0,texec=>0});
my $host;
my $service;
foreach (sort { $service_data{$b}{check_execution_time} <=> $service_data{$a}{check_execution_time} } keys %service_data) {
	if ($service_data{$_}{active_checks_enabled}==1) {
		$host=$service_data{$_}{host_name};
		$service=$service_data{$_}{service_description};
		print "Host: $host Service: $service Check Time: ".$service_data{$_}{check_execution_time}."\n";
		$stats{_all_}{texec}+=$service_data{$_}{check_execution_time};
		$stats{_all_}{tnum}++;
		$stats{$service}={texec=>0,tnum=>0} if !defined($stats{$service});
		$stats{$service}{texec}+=$service_data{$_}{check_execution_time};
		$stats{$service}{tnum}++;
	}
}
print "\n";
printf "Service: $_   Average Execution Time: %.3f (sec)  NumChecks: %d\n",($stats{$_}{texec}/$stats{$_}{tnum}),$stats{$_}{tnum} foreach (sort { $stats{$a}{texec}/$stats{$a}{tnum} <=> $stats{$b}{texec}/$stats{$b}{tnum} } keys %stats);

printf "\nTotal Execution Time: %d (sec)   NumChecks: %d   Average Time: %.3f (sec)\n",$stats{'_all_'}{texec},$stats{'_all_'}{tnum},($stats{'_all_'}{texec}/$stats{'_all_'}{tnum});

