#!/bin/bash
#
# start_wireless.sh v1.1 2005/06
#
# script for starting wireless interface. uses the wpa_supplicant
# daemon, sets the essid and waits for successfull authentication from
# wpa_supplicant to do dhcp on the wireless interface.
#
# very useful when used in combination with sudo to allow non-root
# users to setup wireless network.
#
# Copyright (C) 2005 < pjvenda (at) pjvenda org >
#
# Distributed under the terms of the GNU Public License Agreement (GPLv2)
# http://www.fsf.org/licensing/licenses/gpl.html or
# http://www.fsf.org/licensing/licenses/gpl.txt
#
# Changelog
# =========
#
# v1.1 - 2005/06/13
# - changed dhcp clients and interface management into something less gentoo
# - added killswitch verification
# - use first wireless device found. don't rely on static values
#
# v1.0 - 2005/03/04
# - first version
#

IWCONFIG=/usr/sbin/iwconfig
IFCONFIG=/sbin/ifconfig
DHCPCD=/sbin/dhcpcd
WPA_CLI=/usr/bin/wpa_cli
WETH_DEVICE=$(${IWCONFIG} 2>/dev/null | tr -s " " | cut -d ' ' -f 1)

if [ -z "${WETH_DEVICE}" ]; then
	echo "no wireless devices found."
	exit 1;
else
	echo "found wireless ethernet device: ${WETH_DEVICE}"
fi

if [ ! -z "$(${IWCONFIG} ${WETH_DEVICE} | grep ${WETH_DEVICE} | egrep "radio.*off")" ]; then
	echo "device ${WETH_DEVICE} has radio off. Use kill-switch button to turn it on."
	exit 1;
fi
		
echo -n "stopping wireless interface ... "
${IFCONFIG} ${WETH_DEVICE} down
echo "done"
echo -n "initializing wireless interface ... "
${IWCONFIG} ${WETH_DEVICE} essid "e-U" key open
echo "done"
echo -n "starting wpa_supplicant daemon ... "
/etc/init.d/wpa_supplicant start 2>&1 > /dev/null
echo "done"
sleep 1
echo -n "waiting for authentication process to finish successfully "
while(true); do
	if [ ! -z "$(${WPA_CLI} status | grep "Supplicant PAE state" | grep AUTHENTICATED)" ]; then
		echo " done"
		echo -n "getting ip ... "
		${DHCPCD} ${WETH_DEVICE}
		echo "done"
		break;
	else
		sleep 2;
		echo -n ".";
	fi
done
