#!/bin/sh
#
# Copyright (c) Phillip Hellewell.  March 2004.

# Sanity check
[ "$SCHEME" != "auto" ] && exit 0
[ -z "$DEVICE" ] && exit 0
[ -z "$IWPATH" ] && exit 0

# Default variables
NO_AP="44:44:44:44:44:44"
BEST_SCHEME="default"
BEST_LINK_QUALITY="-1"

# Load wireless auto settings (list of schemes to try)
if [ -r ./wireless_auto.opts ] ; then
    . ./wireless_auto.opts
else
    . /etc/pcmcia/wireless_auto.opts
fi

# Determine where the wireless settings are
if [ -r ./wireless.opts ] ; then
	WIRELESS_OPTS="./wireless.opts"
else
	WIRELESS_OPTS="/etc/pcmcia/wireless.opts"
fi

load_wireless_settings ()
{
	# Reset a few settings in case they aren't specified explicitly
	# in the wireless options file.
	INFO=""
	NICKNAME=""
	ESSID=""
	KEY=""

	. $WIRELESS_OPTS
}

# If we leave out this step, it will never find an Acess Point
ifconfig $DEVICE up

for i in $SCHEMES ; do
	SCHEME=$i
	ADDRESS="$SCHEME,$SOCKET,$INSTANCE,$HWADDR"
	log echo "wireless_auto: Testing SCHEME $SCHEME"

	# Load wireless site-specific settings for this scheme
	load_wireless_settings

	# Set ESSID to test this configuration
	log $IWPATH/iwconfig $DEVICE essid \"$ESSID\"

	# Give it a second to try and find an Access Point
	sleep 1

	# Test for an access point
	FOUND_AP=$($IWPATH/iwconfig $DEVICE | grep "Access Point" | awk '{for(i=1;i<NF;i++) {if ($i=="Point:") print $(i+1)}}')
	[ "$FOUND_AP" = "$NO_AP" ] && continue
	log echo "wireless_auto: Found AP: $FOUND_AP \"$COMMAND\""

	# Test for link quality
	LINK_QUALITY=$($IWPATH/iwconfig $DEVICE | grep "Link Quality" | awk '{print $2}' | cut -d: -f2 | cut -d/ -f1)
	log echo "wireless_auto: Link qualtity: $LINK_QUALITY"
	if [ "$LINK_QUALITY" -gt "$BEST_LINK_QUALITY" ] ; then
		BEST_LINK_QUALITY=$LINK_QUALITY
		BEST_SCHEME=$SCHEME
	fi
done

# Now choose the scheme with the best link quality, or default if no APs found
SCHEME=$BEST_SCHEME
ADDRESS="$SCHEME,$SOCKET,$INSTANCE,$HWADDR"
log echo "wireless_auto: Best scheme: $SCHEME"
load_wireless_settings

