#!/bin/sh
#
# Test whether we can ping the supplied IP address

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "ping-test FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get networking commands into our PATH
PATH=/sbin:/usr/etc/sbin:/usr/etc:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#----------------------------------------------------------"
#!perl -w
# line 31

sub usage(;$)
{
   my $fh = shift || STDOUT;
   print $fh <<ENDUSAGE;
Usage: $0 ipaddress [timeout]

Exits with return code 0 if the address is pingable, and 1 if it is not.

ENDUSAGE
}


my $ip = shift;
my $timeout = shift || 5;

if( !$ip ) {
   usage( STDERR );
   exit 1;
}

if( $ip eq '--help' ) {
   usage();
   exit 0;
}

# Ensure that ping is in the path
$ENV{PATH} = "$ENV{PATH}:/bin:/usr/sbin";

my $uname = `uname`;
chomp( $uname );
my $opts;
if( $uname eq 'Linux' ) {
   # Two different versions of ping, one doesn't have the timeout
   my $gotwait = 0;
   if( open( PINGTEST, "ping -help 2>&1|" )) {
      while( <PINGTEST> ) { $gotwait = 1 if( /-w/ ); }
      close( PINGTEST );
   }
   $opts = $gotwait ? "-c 2 -w $timeout $ip" : "-c 2 $ip";
} elsif( $uname eq 'FreeBSD' ) {
   $opts = "-c 2 -t $timeout $ip";
} elsif( $uname eq 'SunOS' ) {
   $opts = "$ip $timeout";
} elsif( $uname eq 'Darwin' ) {
   # 10.3 doesn't have the timeout option
   my $gottimeout = 0;
   if( open( PINGTEST, "ping -help 2>&1|" )) {
      while( <PINGTEST> ) { $gottimeout = 1 if( /-t/ ); }
      close( PINGTEST );
   }
   $opts = $gottimeout ? "-c 2 -t $timeout $ip" : "-c 2 $ip";
} else {
   die "Sorry, unsupported operating system '$uname'\n";
}

# Run the command, output is unimportant
open( PING, "ping $opts >/dev/null 2>/dev/null|" )
  or die "Can't run ping: $!\n";
my @out = <PING>;
close( PING );

my $return = $? >> 8;
if( $return ) {
   print "Failure\n";
   exit 1;
} else {
   print "Success\n";
   exit 0;
}
