#!/bin/sh
#  $Id: testssid,v 1.3 2003/03/20 11:22:16 andrew Exp $
#
#   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

TESTSSID="$1"

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

if [ "$LINKPWR" -gt 5 ] ; 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
	else
		# we are configured but not for this SSID.
		RESULT=1
	fi
	exit $RESULT
fi	

iwconfig $INTERFACE essid "$1"

#check first for WEP network
iwconfig $INTERFACE key 0000-0000-00

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

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

# echo "iwgetid $INTERFACE | cut -f2 -d: | cut -f2 -d\\\""
# echo "cat /proc/net/wireless | grep $INTERFACE | tr -s ' ' | cut -f4 -d' ' | cut -f1 -d."

#FOUNDSSID="`iwgetid $INTERFACE | cut -f2 -d: | cut -f2 -d'\"'`"

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

# Turn the Key off again. So Scripts can handle the WEP procedure..

iwconfig $INTERFACE key off
if [ "$LINKPWR" -gt 5 ] ; then
  echo "found $TESTSSID on interface $INTERFACE (WEP)"
  RESULT=0
else
  # here we are... check if we now have a link without WEP
  LINKPWR="`cat /proc/net/wireless | grep $INTERFACE | tr -s ' ' | cut -f4 -d' ' | cut -f1 -d.`"
  if [ "$LINKPWR" -gt 4 ] ; then
	  echo "found $TESTSSID on interface $INTERFACE"
	  RESULT=0
  else 
  	echo "$TESTSSID not found"
        RESULT=1
  fi
fi

exit $RESULT

