#!/bin/bash
# $Id: testping,v 1.5 2002/02/27 06:35:25 andrew Exp $
#
#   Script to assist in locating us on a particular network by confirming
#   that we manage to hit a specified host with a quick 'ping'. We actually
#   use 'fping' because it's waaay quicker.
#
#   Written by Andrew McMillan <andrew@mcmillan.net.nz>, 10th December 1999
#
#   [$INTERFACE,]$IPTOFIND,$IPTOUSE
#

# Turn on execution tracing, for debugging...
[ "$DEBUGWHEREAMI" = "1" ] && set -o xtrace

IFACE=${1/,*}
IPTOUSE=${1/*,}
IPTOFIND=${1/,$IPTOUSE}
if [ "$IFACE" = "$IPTOFIND" ] ; then
  # We can also set $INTERFACE externally and that will be used as the default.
  INTERFACE=${INTERFACE:-"eth0"}
else
  INTERFACE=${IFACE}
  IPTOFIND=${IPTOFIND/$INTERFACE,}
fi

ifconfig $INTERFACE $IPTOUSE >/dev/null 2>&1

#   Note that the timeout on fping is set very low (30 mS - -t30) so that
#   the host will need to be close for this to work.  Most LANs will
#   get a response in well under 30mS, but if we fail we will double
#   the interval (-B2 ) five times before giving up.
#
if [ "`fping -a -B2 -i5 -r5 -t30 $IPTOFIND`" = "$IPTOFIND" ] ; then
  #   Leave the interface running in this case
  RESULT=0
else
  # echo "Not found"
  RESULT=1
  #   Downing the interface might seem a good idea, but it makes our next
  #   attempt much slower.  Better to down it after all attempts have failed. (in whereami.conf)
  # ifconfig $INTERFACE down
  ifconfig $INTERFACE 0.0.0.0 >/dev/null 2>&1
fi

exit $RESULT
