#!/bin/bash
#
# $Id: testarp,v 1.11 2004/10/05 20:47:22 andrew Exp $
#
# by Andrew McMillan, Catalyst IT Ltd, (c) 2001 licensed
# for use under the GPL version 2
#
# Thanks to Alexander Clouter for some of the basis of this script :-)
#
#   [$INTERFACE,]$MAC_ADDRESS,$IP_ADDRESS[,$IP_TO_USE]
#
# Turn on execution tracing, for debugging...
[ "$DEBUGWHEREAMI" = "1" ] && set -o xtrace

# Split out our parameters.  This is getting silly!
case "$1" in
  *,*,*,*)
    # All four!  Easy :-)
    IFACE=${1/,*,*,*}
    IP_TO_USE=${1/*,*,*,}
    MIDDLE=${1/$IFACE,}
    MAC_ADDRESS=${MIDDLE/,*}
    MIDDLE=${MIDDLE/$MAC_ADDRESS,}
    IP_ADDRESS=${MIDDLE/,*}
    ;;
  *,*:*,*)
    # Must be IF,MAC,TARGET
    IFACE=${1/,*}
    IP_ADDRESS=${1//*,}
    MAC_ADDRESS=${1/$IFACE,}
    MAC_ADDRESS=${MAC_ADDRESS/,$IP_ADDRESS}
    ;;
  *,*,*)
    # Must be MAC,TARGET,OUR_IP
    MAC_ADDRESS=${1/,*}
    IP_TO_USE=${1//*,}
    IP_ADDRESS=${1/$MAC_ADDRESS,}
    IP_ADDRESS=${IP_ADDRESS/,$IP_TO_USE}
    ;;
  *:*,*)
    # Must be MAC,TARGET
    MAC_ADDRESS=${1/,*}
    IP_ADDRESS=${1/*,}
    ;;
  *)
    # Invalid
    logger -p user.error -t whereami -i "testarp: bogus parameter '$1'"
    exit 2
    ;;
esac

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

IFSTATE="`ifconfig | egrep \"^${INTERFACE}[\t ]\"`"
if [ "$IFSTATE" = "" ] ; then
  # Some systems need the interface "up", some don't
  ifconfig $INTERFACE up > /dev/null 2>&1
fi

if (arping -f -w1 -D -I $INTERFACE $IP_ADDRESS | grep -i -e $MAC_ADDRESS > /dev/null 2>&1) ; then
  if [ "$IP_TO_USE" != "" ] ; then
    # Configure the interface if successful, and we have an IP to use
    ifconfig $INTERFACE $IP_TO_USE >/dev/null 2>&1
  fi
  RESULT=0
else
  # Be a tidy kiwi, and put the interface back how we found it...
  if [ "$IFSTATE" = "" ] ; then
    ifconfig $INTERFACE down > /dev/null 2>&1
  fi

  # echo "Not found"
  RESULT=1
fi

exit $RESULT
