#!/bin/bash
# $Id: testping,v 1.6 2004/10/19 01:04:06 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.
#
RESULT=1
if [ -x /usr/bin/fping ] ; then
  if [ "`fping -a -B2 -i5 -r5 -t30 $IPTOFIND`" = "$IPTOFIND" ] ; then
    #   Leave the interface running in this case
    RESULT=0
  fi
else
  # Fall back to something that will work without installing fping
  # We only try a single ping, since we want to be as quick as possible
  # and we expect to be detecting a LAN ip address.
  if ! /bin/ping -c 1 -n -q $IPTOFIND | grep "100% packet loss" >/dev/null ; then
    RESULT=0
  fi
fi

if [ "$RESULT" = "1" ] ; then
  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.
  # (i.e. if you want to do that, do it in whereami.conf)
  ifconfig $INTERFACE 0.0.0.0 >/dev/null 2>&1
fi

exit $RESULT
