#!/bin/sh

if [ -z $1 ]; then
	IFACE=wifi0
fi

killall dhclient 2>/dev/null
ifconfig $IFACE up
iwlist $IFACE scan > /tmp/iws.cellchoose
ESSID=`grep -m 1 ESSID /tmp/iws.cellchoose | sed -r 's/.*ESSID:"(.*)"/\1/'`
CHANNEL=`grep -m 1 Frequency /tmp/iws.cellchoose | sed -r 's/.*\(Channel\ (.*)\)/\1/'`
KEY=`grep -m 1 Encryption /tmp/iws.cellchoose | sed -r 's/.*key:(.*)/\1/'`
if [ $KEY = on ]; then
	echo "Encryption key needed, keys in hex unless prefixed with s:"
	echo -n "Enter key: "
	read KEY
fi
echo -e "\tESSID: $ESSID\n\tChannel: $CHANNEL\n\tEncryption key: $KEY"
iwconfig $IFACE essid "$ESSID" channel $CHANNEL key "$KEY"
rm /tmp/iws.cellchoose
dhclient $IFACE
