#! /bin/sh
. /etc/default/lejos
. ${LEJOS_HOME}/bin/funcs.sh
log "Configure WiFi"
# get our network address
LJBIN=${LEJOS_HOME}/bin
HOSTNAME=`hostname`
# Now we start wlan
# kill any existing processes
if [ -f /var/run/wifidhcp.pid ]; then
  kill `cat /var/run/wifidhcp.pid`
fi
killall wpa_supplicant 2> /dev/null
# check for interface
iface=`ifconfig -a | grep wlan0`
if [ "$iface" = "" ]; then
  log "No device found"
  exit
fi
# turn off power saving mode, makes some devices work better
iwconfig wlan0 power off 2> /dev/null
log "Check config"
# start wpa_supplicant note must use the Lego version not the default system
if [ -f ${LEJOS_HOME}/config/wpa_supplicant.conf ];
then
  log "Use lejos config"
  config=${LEJOS_HOME}/config/wpa_supplicant.conf
else
  log "Use system config"
  config=/etc/wpa_supplicant.conf
fi
if [ ! -f $config ];
then
  log "No wpa config"
  ${LJBIN}/wpa_supplicant -B -Dwext -iwlan0 -c${LEJOS_HOME}/config/base_wpa_supplicant.conf > /dev/null 2>&1
  exit
fi
ifconfig wlan0 0.0.0.0
log "Find access point"
${LJBIN}/wpa_supplicant -B -Dwext -iwlan0 -c$config > /dev/null 2>&1
count=10
while [ $count -gt 0 ]; do
  sleep 1 
  log "Searching: $count"
  state=`wpa_cli status | grep state 2> /dev/null`
  case $state in
    *COMPLETED) break;;
    *) let count=count-1;;
  esac
done 
if [ $count -eq 0 ]; then
  warning "No AP found"
  exit
fi
apname=`wpa_cli status | grep sid 2> /dev/null`
apname=${apname:29}
log "AP $apname"
# get ip address etc.
log "Request address"
udhcpc --background --retries=10 --timeout=2 -i wlan0 -h ${HOSTNAME} --pidfile /var/run/wifidhcp.pid > /dev/null &
count=10
while [ $count -gt 0 ]; do
  log "Waiting: $count"
  state=`ifconfig wlan0 | grep "inet" 2> /dev/null`
  if [ "$state" != "" ]; then
    break;
  fi
  let count=count-1
  sleep 1
done 
if [ $count -eq 0 ]; then
  warning "Failed to get IP"
  if [ -f /var/run/wifidhcp.pid ]; then
    kill `cat /var/run/wifidhcp.pid`
  fi
  exit
fi
state=`expr match "$state" '.*addr:\(.*\..*\..*\..*\)  Bcast.*'`
log "IP $state"
