#!/bin/bash
# z2netcfg Wireless GUI for the Zipit Z2
# scripted by mozzwald http://www.mozzwald.com
# inspiration from rkdavis http://www.russelldavis.org

#Suppress GTK errors so xdialog works properly
export XDIALOG_NO_GMSGS=1
export DISPLAY=:0

#######################
# Begin Variables
#######################
#TODO: Get some arguments from command line
#http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
args=("$@")
STARTUPCONNECT=0
RESULTSFILE=/tmp/z2scanresults
DEVICE=wlan0
WPACONFIG="/etc/wpa_supplicant.conf"
#######################
# End Variables
#######################

#######################
# Begin Functions
#######################
function scan {
#echo Scanning for wireless networks
ifconfig $DEVICE up
iwlist $DEVICE scan > $RESULTSFILE
let COUNT=0
exec 3< $RESULTSFILE
while read <&3; do
#Get the ESSID
if `echo $REPLY | grep -q 'ESSID'`; then
  # First check if the last ESSID was WPA or not
  if [ "${WPA[$COUNT]}" != "yes" ]; then
    WPA[$COUNT]="no"
  fi
  ((COUNT++))
  ESSID[$COUNT]=`echo $REPLY | sed 's/ESSID:"//' | sed 's/"//'`
#  echo ${ESSID[$COUNT]}
fi
#Check for Encryption
if `echo $REPLY | grep -q 'Encryption key:'`; then
  CRYPT[$COUNT]=`echo $REPLY | sed 's/Encryption key://'`
#  echo Encryption: ${CRYPT[$COUNT]}
fi
#Check the quality
if `echo $REPLY | grep -q 'Quality='`; then
  QUALITY[$COUNT]=`echo $REPLY | sed 's/Quality=//' | sed 's_/.*__'`
#  echo ${QUALITY[$COUNT]}
fi
#Check for WPA
if `echo $REPLY | grep -q 'IE:'`; then
  #WPA yes
  WPA[$COUNT]="yes"
fi
done

if [ "${WPA[$COUNT]}" != "yes" ]; then
  WPA[$COUNT]="no"
fi

}

function scandialog {
# Create the scan dialog
let XCOUNT=COUNT+1
echo "XCOUNT: $XCOUNT"
echo "#!/bin/bash
Xdialog --title \"Wifi Networks\" \\
        --menu \"Choose a network\" 24 51 $XCOUNT \\" > /tmp/dialog.sh
let DCOUNT=1
until [ $DCOUNT -gt $COUNT ]; do
  if [ "${CRYPT[$DCOUNT]}" == "on" ]; then
    if [ "${WPA[$DCOUNT]}" == "yes" ]; then
      CIPHER[$DCOUNT]="WPA"
      CIPHER[${ESSID[$DCOUNT]}]="WPA"
      echo ${CIPHER[${ESSID[$DCOUNT]}]}
    else
      CIPHER[$DCOUNT]="WEP"
      CIPHER[${ESSID[$DCOUNT]}]="WEP"
    fi
  else
    CIPHER[$DCOUNT]="None"
    CIPHER[${ESSID[$DCOUNT]}]="None"
  fi
  
  echo "ESSID: ${ESSID[$DCOUNT]} Crypt: ${CRYPT[$DCOUNT]} WPA: ${WPA[$DCOUNT]} Cipher: ${CIPHER[$DCOUNT]}"
  echo -e "\"${ESSID[$DCOUNT]}\" \"${CIPHER[$DCOUNT]}, ${QUALITY[$DCOUNT]}%\" \\" >> /tmp/dialog.sh
  ((DCOUNT++))
done
#echo $DCOUNT
#echo $COLUMN
echo "\"Cancel\" \"N/A\" 2>&1" >> /tmp/dialog.sh
chmod 777 /tmp/dialog.sh
CHOICE=`/tmp/dialog.sh`
rm /tmp/dialog.sh
# Check if canceled
if [ "$CHOICE" == "" -o "$CHOICE" == "None" ]; then
  echo Connect Canceled
else
  # Find out if we need encryption key
  echo ${CIPHER[$CHOICE]}
  if [ ${CIPHER[$CHOICE]} = "WPA" ] || [ ${CIPHER[$CHOICE]} = "WEP" ]; then
  Xdialog --title "Encryption Key" \
        --inputbox "Enter your encryption key \
        or passphrase" 18 45 2>/tmp/passphrase.tmp.$$
  retval=$?
  PASSPHRASE=`cat /tmp/passphrase.tmp.$$`
  rm -f /tmp/passphrase.tmp.$$

  case $retval in
    0)
      # Make sure the Passphrase is the proper length
      if [ "${CIPHER[$CHOICE]}" = "WPA" ] ; then
	if [ "${#PASSPHRASE}" -ge "8" ] && [ "${#PASSPHRASE}" -le "63" ]; then
	  echo "WPA Passphrase-> $PASSPHRASE <-is good" #>/dev/null
	else
	  echo "WPA Passphrase not proper length!"
	fi
      elif [ "${CIPHER[$CHOICE]}" = "WEP" ] ; then
        # Check if it's Hex (10 or 26) or passphrase
	echo nothing >/dev/null
      fi
      ;;
    1)
      echo "Cancel pressed.";;
    255)
      echo "Box closed.";;
  esac
  else
    echo "No encryption key needed"
  fi

  #Check if CHOICE is in wpa config file, if not, ask to add
  NOTSAVED=1
  while read ; do
    if [ -n "`echo "$REPLY" | grep "$CHOICE"`" ] ; then
      NOTSAVED=0
    fi
  done <"$WPACONFIG"
  if [ "$NOTSAVED" = "1" ] ; then
    # Get required information: Encryption keys, etc
    # then ask if we should save for future use
    echo "Network not saved"
    Xdialog --wrap --title "Save Network?"\
        --yesno "This network is not saved. Would you \
                 like to save this access point \
                 for future use?" 0 0

    case $? in
      0)
	if [ "${CIPHER[$CHOICE]}" = "WPA" ] ; then
          wpa_passphrase "$CHOICE" "$PASSPHRASE" >> "$WPACONFIG"
	elif [ "${CIPHER[$CHOICE]}" = "WEP" ] ; then
	  THEPHRASE='\nnetwork={\n    ssid="$CHOICE"\n    key_mgmt=NONE    wep_key0="$PASSPHRASE"\n}'
	  echo "$THEPHRASE" >> "$WPACONFIG"
	fi
	;;
      1)
        echo "No chosen.";;
      255)
        echo "Box closed.";;
    esac
  fi

  # then connect
  #connect
fi
}

function connect {
#TODO: Check if wpa_supplicant/dhclient are running already and figure out what to do.
#Maybe use wpa_cli if connected
wpa_supplicant -B -i$DEVICE -c "$WPACONFIG"
dhclient "$DEVICE" -1 > /dev/tty0
nolease=$?
if [ $nolease -eq 2  ] ;  then
  Xdialog --wrap --title "Connect Failed" \
        --yesno "Unable to connect network. Would you like to scan for networks?" 0 0

case $? in
  0)
    # Yes
    scandialog
  ;;
  1)
    # No
  ;;
  255)
    # Cancel
  ;;
esac
else
  ifconfig $DEVICE > $RESULTSFILE
  exec 3< $RESULTSFILE
  while read <&3; do
    if `echo $REPLY | grep -q 'inet addr:'`; then
      IP=`echo $REPLY | sed 's/inet addr://' | sed 's_B.*__'`
    fi
  done
  Xdialog --title "Connected!" \
	--msgbox "Connected! Your IP is $IP" 10 41
fi
}

function trayicon {
  # Get ip address to diplay in tray icon
  ifconfig $DEVICE > $RESULTSFILE
  exec 3< $RESULTSFILE
  while read <&3; do
    if `echo $REPLY | grep -q 'inet addr:'`; then
      IP=`echo $REPLY | sed 's/inet addr://' | sed 's_B.*__'`
    fi
  done
  zenity --notification --text="$DEVICE AP:$CHOICE IP:$IP" \
    --window-icon="/usr/share/lxpanel/images/gnome-netstatus-txrx.png"
}

function optionsdialog {
  # Display a list of options after clicking on the tray icon
  OPTION=`Xdialog --backtitle "Network Options" \
	--title "Network Options" \
        --menu "Please choose an option" 26 46 4 \
	"Connect to a Network"  "" \
	"Disconnect" "" \
	"Reload Modules" "" \
	"About" "" \
	"Quit netcfg" "" 2>&1`
  echo "Option: $OPTION"
  if [ "$OPTION" == "Connect to a Network" ]; then
    echo "Another Network Please"
    scan
    scandialog
  fi
  if [ "$OPTION" == "Disconnect" ]; then
    echo "Disconnect Please"
    disconnect
  fi
  if [ "$OPTION" == "About" ]; then
    Xdialog --title "About z2netcfg" \
	--msgbox "Written by mozzwald (http://www.mozzwald.com) with some
	inspiration from rkdavis (http://www.russeldavis.org)" 10 41
  fi
  if [ "$OPTION" == "Quit netcfg" ]; then
    echo "Killing z2netcfg"
    kill $$
  fi

}

function disconnect {
  ifconfig $DEVICE down
}

#######################
# End Functions
#######################

#######################
# Begin Main
#######################

if [ $STARTUPCONNECT -eq 1 ]; then
  # Connect using wpa_supplicant.conf
  connect
fi

# Run a loop that displays the tray icon and when clicked runs 
# an options dialog to rescan, disconnect, etc. Then reloads icon
# when done
#while true; do
#  trayicon
#  optionsdialog
#done
optionsdialog

#######################
# End Main
#######################
