#!/usr/bin/perl -w
#
# pc 20090406

use strict ;
use lib   "/opt/nagios/libexec" ;
use utils qw($TIMEOUT %ERRORS &print_revision &support) ;
use vars  qw($PROGNAME) ;
use Getopt::Long ;

sub  best($$) ;
sub worst($$) ;
sub reach($$) ;

$PROGNAME = "check_multi" ;

my ( $multi_host, $combine_type, $plugin, $options ) ;
$multi_host = '127.0.0.1' ;
$options = '' ;
GetOptions(
	"hostname=s"	=> \$multi_host,	"H=s"	=> \$multi_host,
	"combine=s"	=> \$combine_type,	"C=s"	=> \$combine_type,
	"plugin=s"	=> \$plugin,		"p=s"	=> \$plugin,
	"options=s"	=> \$options,		"o=s"	=> \$options
) ;

unless ( $combine_type =~ m/^(reach|best|worst)$/ ) {
	print "UNKNOWN combination type \"$combine_type\"\n" ;
	exit $ERRORS{'UNKNOWN'} ;
}

unless ( -x $plugin ) {
	print "plugin \"$plugin\" not found or not executable\n" ;
	exit $ERRORS{'UNKNOWN'} ;
}

my @host_list   = split ',', $multi_host ;
my $result_msgs = '' ;
my $combine_func = \&{"$combine_type"} ;
my $final_result = $ERRORS{'UNKNOWN'} ;

my $h ;
foreach $h ( @host_list ) {
	my $msg = `$plugin -H $h $options` ;
	my $res = ( $? >> 8 ) ;
	$msg =~ s/\|.*$// ;
	chomp $msg ;
	$result_msgs .= "$h: $msg\n" ;
	my $running_result = &$combine_func( $final_result, $res ) ;
#	warn "result for this check is $res\ncombined result is $running_result\n" ;
	$final_result = $running_result ;
}

print "$result_msgs" ;
exit $final_result ;

sub reach($$){
	# REACH :
	#   O W C U
	# O o w w o
	# W w w w w
	# C w w c c
	# U o w c u
	
	my @reach_tab = (
		[ 0, 1, 1, 0 ],
		[ 1, 1, 1, 1 ],
		[ 1, 1, 2, 2 ],
		[ 0, 1, 2, 3 ]
	) ;
	my ( $in1, $in2 ) ;
	( $in1, $in2 ) = @_ ;
	$in1 = 3 if $in1 > 3 or $in1 < 0 ;
	$in2 = 3 if $in2 > 3 or $in2 < 0 ;
	return $reach_tab[$in1][$in2] ;
}

sub best($$) {
	# BEST :
	#   O W C U
	# O o o o o
	# W o w w w
	# C o w c c
	# U o w c u

	my @best_tab = (
		[ 0, 0, 0, 0 ],
		[ 0, 1, 1, 1 ],
		[ 0, 1, 2, 2 ],
		[ 0, 1, 2, 3 ]
	) ;
	my ( $in1, $in2 ) ;
	( $in1, $in2 ) = @_ ;
	$in1 = 3 if $in1 > 3 or $in1 < 0 ;
	$in2 = 3 if $in2 > 3 or $in2 < 0 ;
	return $best_tab[$in1][$in2] ;
}

sub worst($$) {
	# WORST :
	#   O W C U
	# O o w c o
	# W w w c w
	# C c c c c
	# U o w c u

	my @worst_tab = (
		[ 0, 1, 2, 0 ],
		[ 1, 1, 2, 1 ],
		[ 2, 2, 2, 2 ],
		[ 0, 1, 2, 3 ]
	) ;
	my ( $in1, $in2 ) ;
	( $in1, $in2 ) = @_ ;
	$in1 = 3 if $in1 > 3 or $in1 < 0 ;
	$in2 = 3 if $in2 > 3 or $in2 < 0 ;
	return $worst_tab[$in1][$in2] ;
}
