#!/bin/bash 
#
#   Script to assist in locating us on a particular wireless network
#
#   Written by Andrew McMillan <awm@debian.org>, 15th November 2002
#   Changed by Adrian Woizik <morrow@unfug.org>, 06th March 2003
#
#   $1 is the parameters we are finding, comma-separated
#     - Expected SSID
#   
#

[ "$DEBUGWHEREAMI" != "" ] && set -o xtrace

WLANTIMEOUT=${TIMEOUT:-"2"}
case $1 in
  *,*)
    TESTSSID="${1/,*}"
    WEPKEY="${1/*,}"
    ;;
  *)
    # WEP off
    WEPKEY=""
    TESTSSID="$1"
    ;;
esac

if [ "${WEPKEY}" != "" ] ; then
  iwconfig $INTERFACE key "${WEPKEY}"
fi

LINKPWR="`cat /proc/net/wireless | grep $INTERFACE | tr -s ' ' | cut -f4 -d' ' | cut -f1 -d.`"

if [ "`grep -E '(driverloader|ndiswrapper)' /proc/modules`" != "" ] ; then
  # ndiswrapper and the linuxant driverloader only return a binary value
  MINPWR=0
else
  MINPWR=5
fi

if [ "$LINKPWR" -gt "$MINPWR" ] ; then
	FOUNDSSID="`iwgetid $INTERFACE | cut -f2 -d: | cut -f2 -d'\"'`"
	if [ "$FOUNDSSID" = "$TESTSSID" ] ; then
		# we are already configured, exit and do not touch iwconfig.
		RESULT=0
	  exit $RESULT
	else
		# we are configured but not for this SSID.
		RESULT=1
	fi
fi	

iwconfig $INTERFACE essid on
iwconfig $INTERFACE essid "${TESTSSID}"

# be sure that $INTERFACE is up, for linkstat
ifconfig $INTERFACE up

# How long to wait?  1 second is _usually_ enough, but not always
sleep ${WLANTIMEOUT}

LINKPWR="`cat /proc/net/wireless | grep $INTERFACE | tr -s ' ' | cut -f4 -d' ' | cut -f1 -d.`"

if [ "$LINKPWR" -gt 5 ] ; then
  iwconfig $INTERFACE key restricted
  [ "$DEBUGWHEREAMI" != "" ] && echo "Found power of ${LINKPWR} for $TESTSSID on interface $INTERFACE (WEP)"
  RESULT=0
else
  # Turn the Key off again to look for a non-WEP AP
  iwconfig $INTERFACE key off
  LINKPWR="`cat /proc/net/wireless | grep $INTERFACE | tr -s ' ' | cut -f4 -d' ' | cut -f1 -d.`"
  if [ "$LINKPWR" -gt 4 ] ; then
    [ "$DEBUGWHEREAMI" != "" ] && echo "found $TESTSSID on interface $INTERFACE"
	  RESULT=0
  else 
    [ "$DEBUGWHEREAMI" != "" ] && echo "$TESTSSID not found"
    RESULT=1
  fi
fi

exit $RESULT

