#! /usr/bin/perl -w
#
# check_hopcount.pl - nagios plugin 
# 
#
# Copyright (C) 2004 Gerd Mueller / Netways GmbH
#
# 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; either version 2
# of the License, or (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#

use POSIX;
use strict;
use lib "/usr/local/nagios/libexec";

use utils qw($TIMEOUT %ERRORS &print_revision &support);

use Net::SNMP;
use Getopt::Long;
Getopt::Long::Configure('bundling');

my $opt_c=2;
my $opt_w=2;
my $opt_h;
my $hostname="localhost";

my $status;

my $PROGNAME = "check_hopcount";

use Net::Traceroute;

$status = GetOptions(
		"h"   => \$opt_h, "help"       => \$opt_h,
		"c=s" =>\$opt_c,
		"w=s" =>\$opt_w,
		"H=s" => \$hostname, "hostname=s" => \$hostname);		

if(!$opt_c || !$opt_w || $opt_h || $status==0) {
	print_usage() ;
}

my $tr = Net::Traceroute->new(host=>$hostname);
my $errorcode = $ERRORS{'OK'};
my $output;

if($tr->found) {
    my $hops = $tr->hops;
    if($hops == 1) {
		$output ="Same subnet";
    } else {
		$output = "Last router is " .$tr->hop_query_host($hops - 1, 0);
    }
    $output=$hops." hops - ".$output;
    if($hops>=$opt_c) {
    	$errorcode = $ERRORS{'CRITICAL'};
    } elsif($hops>=$opt_w) {
    	$errorcode = $ERRORS{'WARNING'};
    } 
    $output.= " | 'hopcount'=".$hops.";".$opt_w.";".$opt_c."\n";
} else {
	$output =' Host ist unknown! \n ';
	$errorcode = $ERRORS{'UNKNOWN'};
}

print $output;
exit $errorcode;


sub print_usage {
					printf "\n";
					printf "check_hopcount -H <HOSTNAME> -w n -c n \n";
					printf "Copyright (C) 2004 Gerd Mueller / Netways GmbH\n";
					printf "\n\n";
					exit $ERRORS{"UNKNOWN"};
				}
				
