#!/usr/bin/perl -w

############################################################################
# Nagios Check script to see if an internet connection is working
#
# Copyright (C)2005 Guy Van Sanden <nocturn00@gmail.com> - http://nocturn.vsbnet.be
#
#    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.
#
# USAGE:
# check_internet 
#
############################################################################

use strict;
use warnings;
use Getopt::Long;
use vars qw($opt_V $opt_h $opt_t $opt_F $PROGNAME);
use lib '/usr/lib/nagios/plugins/';
use utils qw(%ERRORS &print_revision &support);
use Net::Ping;

$PROGNAME="check_internet";

sub print_help ();
sub print_usage ();

$ENV{'PATH'}='';
$ENV{'BASH_ENV'}='';
$ENV{'ENV'}='';
my ( $line, $prevline, $stat, $state ,@device, $msg, $status, $timeout);

$stat="";

#Option checking
Getopt::Long::Configure('bundling');
$status = GetOptions(
                'V'   		=> \$opt_V, 
		'version'    	=> \$opt_V,
                'h'   		=> \$opt_h, 
		'help'       	=> \$opt_h,
		'F=s' 		=> \$opt_F, 
		'Filename=s'   	=> \$opt_F);

# Version
if ($opt_V) {
        print_revision($PROGNAME,'$Revision: 0.1 $');
        exit $ERRORS{'OK'};
}

# Help
if ($opt_h) {
        print_help();
        exit $ERRORS{'OK'};
}

# Filename supplied
if ($opt_F) {
        #$opt_F = shift;
	chomp($opt_F);
	$stat = $opt_F;
}

if ( ! -r $stat ) {
	print "Invalid server file: $stat\n";
       	exit $ERRORS{'UNKNOWN'};
}

open (FH, $stat);
$state = $ERRORS{'OK'};
$msg ="";
my $loopcount=0;

# Now check the servers until one responds
while (<FH>) {
	chomp($_);
        my $server= $_;

	$loopcount++;

	my $p = Net::Ping->new();
        my $retval = $p->ping($_,2);
        $p->close();

	if($retval eq 0) {
		$state = $ERRORS{'OK'};
		$msg = "Connection UP at try $loopcount ($server)";
		last;
	} else {
		$state = $ERRORS{'CRITICAL'};
		$msg = "Connection DOWN at try $loopcount";
	}
}
close (FH);

if ( $state == $ERRORS{'CRITICAL'} ) {
        print "CRITICAL - $msg\n";
} elsif ( $state == $ERRORS{'OK'} )
         { print "OK - $msg\n"; }
exit $state;


sub print_usage () {
        print "Usage: $PROGNAME -F <filename>\n";
}

sub print_help () {
        print_revision($PROGNAME,'$Revision: 0.2 $');
        print "Copyright (c) 2005 Guy Van Sanden\n";
        print "\n";
        print_usage();
        print "Checks if the Internet connection is still up by pinging specified hosts.\n
-F ( --filename=FILE)
        Full path and name to servers file.\n\n";
support();
}


