#!/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
}

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

   return $? >> 8;
}

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 $failed;
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 );
   }
   my $opts = $gotwait ? "-c 2 -w $timeout $ip" : "-c 2 $ip";
   $failed = try_ping( 'ping', $opts );
   if( $failed ) {
      # retry with ping6
      $gotwait = 0;
      if( open( PINGTEST, "ping6 -help 2>&1|" )) {
         while( <PINGTEST> ) { $gotwait = 1 if( /-w/ ); }
         close( PINGTEST );
      }
      $opts = $gotwait ? "-c 2 -w $timeout $ip" : "-c 2 $ip";
      $failed = try_ping( 'ping6', $opts );
   }
} elsif( $uname eq 'SunOS' ) {
   $failed = try_ping( 'ping', "$ip $timeout" );
} else {
   die "Sorry, unsupported operating system '$uname'\n";
}

if( $failed ) {
   print "Failure\n";
   exit 1;
} else {
   print "Success\n";
   exit 0;
}
