#!/bin/sh
#
# Author:  Andrew McMillan
# Written: 8th July 2005 (Debconf5, Helsinki)
#
# This script is designed to help whereami work with the wpasupplicant
# package.  We make the assumption that wpasupplicant is running and
# that you have at least got it working manually, and now you want to
# use it with whereami...
#
# We seem to need to do several things:
# - Configure for null encryption and "open" mode
# - Bring the interface up.
# - Kick the wpa_supplicant daemon
# - Either:
#   - Watch the wpa_cli status output for COMPLETED
#   - Watch the iwconfig output until we see a real encryption key
#

# Turn on execution tracing, for debugging...
[ -n "$DEBUGWHEREAMI" ] && set -o xtrace

MAXATTEMPTS=15

# # Perhaps this is needs to be optional - if so, tell me please!
iwconfig ${INTERFACE} enc "ffff-ffff-ff" enc open

ifconfig ${INTERFACE} up

ACTION=start
if pgrep wpa_supplicant >/dev/null ; then
  ACTION=reload
fi
if [ -x /etc/init.d/wpasupplicant ] ; then
  /etc/init.d/wpasupplicant "${ACTION}"
else
  # Kill any existing supplicant, sleeping briefly if we did so
  pkill wpa_supplicant && sleep 1
  # Start a new supplicant
  /sbin/wpa_supplicant -B -Dwext -i${INTERFACE} -c/etc/wpa_supplicant.conf
  echo "$!" >/var/run/whereami/supplicant.pid
fi

while [ "$MAXATTEMPTS" -gt "0" ] ; do
  if /sbin/wpa_cli -i ${INTERFACE} status | grep 'wpa_state=COMPLETED' >/dev/null ; then
    # Success
    exit 0
  fi
  if [ "`iwconfig ${INTERFACE} | grep Encryption | cut -f3 -d: `" = "restricted" ] ; then
    # Success
    exit 0
  fi
  # Otherwise we loop again until we have exceeded the timeout...
  sleep 1
  MAXATTEMPTS=$(( $MAXATTEMPTS - 1 ))
done

# Failed to work within timeout
if [ -x /etc/init.d/wpasupplicant ] ; then
  /etc/init.d/wpasupplicant stop
else
  pkill wpa_supplicant
fi

exit 1
