#!/usr/bin/perl
# monNetCon  (c) Copyright 1998 Mark Black 

# NOTE:  If you modify this code, you MUST change the version to
#        something over 100 to prevent it being replaced by future
#        versions of this script. 
$version = 2 ;

# monNetCon
# This script is called to test the network connectivity
# Outputs status to stdout in the form  status:info
# status can be 0 or 1.  1 = success, 0 = fail
#          OUTPUT:
#                   1:      - Success
#                   0:info  - Failure
#	   Input args:
#                   -v      - Print script version number
#		    -i      - Instance.  This tells MATd if there is
#		              an instance of the parameter it wishes
#                             to monitor.  Code returns number of 
#                             instances.
#
#         Note:  Exit status of script should always be  0, anything
#	         else indicates an error in the monitoring script.

$input = "" ;
foreach $i (0 .. $#ARGV) {
   $input .= "@ARGV[$i] " ;
}
chop($input) ;

# Output the version if requested
if($input eq "-v") {
    print "$version\n" ;
    exit(0) ;
}

if($input eq "-i") {
    print "1:\n" ;
    exit(0) ;
}

# Discover OS type and set variables for OS type
chop($os = `uname -s`) ;

if($os eq "Linux") {
    $ping = "/bin/ping" ;
    $cargs = "-c 1" ;
    @data = `$ping $cargs $input 2>/dev/null` ;
} elsif($os eq "SunOS") {
    chop($ver = `uname -r`) ;
    ($major, $minor) = split(/\./, $ver) ;
    if($major == 5) {
	$os = "Solaris" ;
        $ping = "/usr/sbin/ping" ;
        $cargs = "" ;
    } else {
        $ping = "/bin/ping" ;
        $cargs = "-c 1" ;
    }
    @data = `$ping $cargs $input 2>/dev/null` ;
} elsif(($os eq "IRIX") | ($os eq "IRIX64"))  {
    $ping = "/bin/ping" ;
    $cargs = "-c 1" ;
    @data = `$ping $cargs $input 2>/dev/null` ;
} elsif($os eq "HP-UX") {
    $ping = "/usr/sbin/ping" ;
    $cargs = "-n 1" ;
    @data = `$ping $input $cargs 2>/dev/null` ;
}

# The output of the Solaris Ping is different.
if($os eq "Solaris") {
    if($? == 0 ) {
	# Ping worked
	  print "1:Connectivity Okay to $input\n" ;
    } else {
	    print "0:Error Connectivity Lost to $input\n" ;
    }
    exit(0) ;
}

# Parse the output from Ping
while ($line = pop(@data)) {
    if($line =~ m/1 packets.*/ ) {
	# This is the appropriate line from ping
	($a, $b, $c, $pass, $e) = split(/\ /, $line, 5) ;
	if($pass) {
	    print "1:Connectivity Okay to $input\n" ;
	} else {
	    print "0:Error Connectivity Lost to $input\n" ;
	}
    }
}



