#! /bin/bash
# Comments to  <awol@awol.no-ip.org> Vers 1.2
# This script requires the dialog package to be installed.
if [ -f  /usr/bin/dialog ] ; then
   echo 
 else
   echo
   echo "Sorry you need '/usr/bin/dialog' for this script..."
   echo
   exit 1
fi
#
: ${DIALOG=dialog}
[ -e ~/.wificonf ] || echo "iwconfig wlan0 mode managed essid awol-test-ap key s:MyLameAsciiKey channel 1" > ~/.wificonf
backtitle="awol's wifi configuration tool."
n=1 ; if n=1
then read iwcommand CARD Mode MODE Essid ESSID Key OLDKEY Channel CHANNEL < ~/.wificonf
KEY=`echo $OLDKEY | sed 's/s\://'`
n=0 ; fi

returncode=0
defaultitem="Card:"
while test $returncode != 1 && test $returncode != 250
do
exec 3>&1
value=`$DIALOG --clear --ok-label "Activate" \
	  --backtitle "$backtitle" \
	  --extra-label "Edit" \
	  --default-item "$defaultitem" \
	  --cancel-label "Exit"\
	  --item-help \
	  --inputmenu "Configure wireless card settings here" \
22 50 16 \
	"Card:"		"$CARD"		"Interface device name" \
	"Mode:"		"$MODE"		"Master or Managed" \
	"Essid:"	"$ESSID"	"WEP access point name" \
	"Key:"		"$KEY"		"ascii key to WEP" \
	"Channel:"	"$CHANNEL"	"Channel to connect" \
2>&1 1>&3`
returncode=$?
exec 3>&-

	case $returncode in
	1)
		"$DIALOG" \
		--clear \
		--backtitle "$backtitle" \
		--msgbox "iwconfig $CARD\n\
			mode $MODE \n\
			essid $ESSID \n\
			key s:$KEY \n\
			channel $CHANNEL" 10 50 \
		--and-widget \
		--yesno "Apply settings before exiting?" 10 50
		case $? in
		0)
			echo "$iwcommand $CARD mode $MODE essid $ESSID key s:$KEY channel $CHANNEL" > ~/.wificonf
			$iwcommand $CARD mode $MODE essid $ESSID key s:$KEY channel $CHANNEL
			;;
		1)
			break
			;;
		esac
		;;
	0)
		case $value in
		*)
			"$DIALOG" \
			--clear \
			--backtitle "$backtitle" \
			--msgbox "iwconfig $CARD\n\
				mode $MODE \n\
				essid $ESSID \n\
				key s:$KEY \n\
				channel $CHANNEL" 10 50 \
			--yesno "Apply Settings Immediately?" 10 50 
			echo "$iwcommand $CARD mode $MODE essid $ESSID key s:$KEY channel $CHANNEL" > ~/.wificonf
			$iwcommand $CARD mode $MODE essid $ESSID key s:$KEY channel $CHANNEL
			;;
		esac
		;;
	2)
		"$DIALOG" \
			--clear \
			--backtitle "$backtitle" \
			--msgbox "$iwcommand $CARD\n\
				mode $MODE \n\
				essid $ESSID \n\
				key s:$KEY \n\
				channel $CHANNEL" 10 50 \
                ;;
	3)
		tag=`echo "$value" |sed -e 's/^RENAMED //' -e 's/:.*/:/'`
		item=`echo "$value" |sed -e 's/^.*:[ ]*//' -e 's/[ ]*$//'`

		case "$tag" in
		Card:)
			CARD="$item"
			;;
		Mode:)
			MODE="$item"
			;;
		Essid:)
			ESSID="$item"
			;;
		Key:)
			KEY="$item"
			;;
		Channel:)
			CHANNEL="$item"
			;;
		*)
			tag=
			;;
		esac
		test -n "$tag" && defaultitem="$tag"
		;;

        255)
                echo "ESC pressed."
                break
                ;;

	esac
done
