#!/bin/bash
#
# This script identifies where I am based on a DHCP assigned address.
#
# Much code copied from Brian Mays PCMCIA package
#
# One day we need to make this work with multiple ethXX devices (or even ppp)
# but for now we'll just stick with eth0
DEVICE=${1:-"eth0"}
RESOLV=/etc/resolv.conf

METHOD=dhcpc
[ -e /sbin/pump ] && METHOD=pump

#
# Ensure DHCP client isn't running
/etc/init.d/dhcpcd stop >>/dev/null 2>&1

# We put all of the following in a subshell as that means that we
# can 'exit' from it OK, which makes it easier to cut and paste
# Brian Mays stuff from the /etc/pcmcia/network script!

(
  /sbin/ifconfig $DEVICE up 0.0.0.0 >>/dev/null 2>&1
  /sbin/route add default dev $DEVICE >>/dev/null 2>&1
  if [ -x /sbin/dhcpcd ] ; then
      if /sbin/dhcpcd -V 2>&1 | grep -q DHCP ; then
          /sbin/dhcpcd -t 10 $DEVICE >/dev/null 2>&1 || exit 1
      else
          # Jump through hoops for lame 0.70-era dhcpcd
          L=/var/run/dhcp-lock-$DEVICE
          /bin/echo "#!/bin/sh\nrm $L" > $L ; chmod +x $L
          /sbin/dhcpcd -c $L $DEVICE >/dev/null 2>&1
          for t in 0 1 2 3 4 5 6 7 8 9 ; do
              sleep 2 ; if [ ! -e $L ] ; then break ; fi
          done
          rm -f $L
          if [ -e /etc/dhcpc/resolv.conf ] ; then
              echo "# $DEVICE begin" > $RESOLV.N
              cat /etc/dhcpc/resolv.conf >> $RESOLV.N
              echo "# $DEVICE end" >> $RESOLV.N
              cat $RESOLV >> $RESOLV.N ; mv $RESOLV.N $RESOLV
          fi
      fi
  elif [ -e /sbin/pump ]; then
      # Might be advisable to set a timeout in your /etc/pump.conf
      /sbin/pump -i $DEVICE 2>&1 | grep -q "failed" && exit 1
  elif [ -x /sbin/dhclient ] ; then
      /sbin/dhclient $DEVICE >/dev/null 2>&1 || exit 1
  else
      exit 1
  fi

  #
  #
  # Chances are we have a valid location now
  #
  LOCATED=1
  if ( ifconfig | grep "192\.168\.2\." >>/dev/null ); then
    LOCATION=catalyst
  elif ( ifconfig | grep "10\.2\.0\." >>/dev/null ); then
    LOCATION=ttpak
  elif ( ifconfig | grep "10\.3\.0\." >>/dev/null ); then
    LOCATION=agp
  elif ( ifconfig | grep "192\.168\.5\." >>/dev/null ); then
    LOCATION=amtrust
  elif ( ifconfig | grep "172\.16\.40\." >>/dev/null ); then
    LOCATION=hbl
  elif ( ifconfig | grep "192\.168\.10\." >>/dev/null ); then
    LOCATION=maudwn
  elif ( ifconfig | grep "192\.168\.0\." >>/dev/null ); then
    LOCATION=neldiag
  elif ( ifconfig | grep "192\.168\.7\." >>/dev/null ); then
    LOCATION=pcnz
  else
    LOCATED=0
    exit 1
  fi

  #
  # We only put the location out if we find one.
  #
  echo $LOCATION >>iwillbe
  LOCATED=1
)
