#!/bin/bash
touch /tmp/interface
touch .wifi
freply=.wifi
if [ $DISPLAY ]; then
  DIALOG=Xdialog
else
  DIALOG=dialog
fi

b=/etc/wifi-radar/wifi-radar.conf.backup
i=/etc/wifi-radar/wifi-radar.conf
inter=`cat $i|grep interface|cut -d " " -f3`
interface=`/sbin/iwconfig 2>/dev/null| cut -d " " -f1 | grep [a-z]`
connected=no

### we have many wireless modules some can cause us problems you can add more here
### if you remove "none" from the list the script will not exit properly
list="ipw2100 ipw2200 ipw3945 zd1201 ndiswrapper none"

if [ ! -f $b ]; then
  cp $i $b
fi

while [ "$connected" == no ]; do
  if [ ! "$interface" == "" ]; then
    connected=yes
  elif [ "$interface" == "" ]; then
    for a in $list; do
      if [ "$a" == none ]; then
        connected=yes
        echo we dont seem to have a driver for your hardware sorry
        echo would you like to try another module?
        echo if you would like to try another module and you know its name 
        echo enter y anything else and we will exit
        read ans
        if [ "$ans" == "y" ]; then
          echo enter your module name
          read a
          echo checking $a
          /sbin/modprobe $a 2>/dev/null
          sleep 1
          interface=`iwconfig 2>/dev/null| cut -d " " -f1 | grep [a-z]`
          if [ ! "$interface" == "" ]; then
            connected=yes
            echo module $a seems to work with your hardware lets try it
            break
          fi
          echo removing $a module
          rmmod $a 2>/dev/null
          echo "sorry that one doesnt seem to work either, bye"
          sleep 2
          exit 0
        else
          exit 0
        fi
      fi
      echo checking $a
      modprobe $a 2>/dev/null
      if [ $a == ipw3945 ]; then
        /sbin/ipw3945d
      fi 
      sleep 1
      interface=`/sbin/iwconfig 2>/dev/null| cut -d " " -f1 | grep [a-z]`
      if [ ! "$interface" == "" ]; then
        connected=yes
        echo module $a seems to work with your hardware lets try it
        break
      fi
      echo removing $a module
      rmmod $a 2>/dev/null
    done
   fi
done

interface=`/sbin/iwconfig 2>/dev/null| cut -d " " -f1 | grep [a-z]`
if [ ! "$inter" == "$interface" ]; then
 echo $inter $interface
  if [ ! "$interface" == "" ]; then
    cat $i | sed s/$inter/$interface/ > $i.tmp
    mv $i $i.bak
    mv $i.tmp $i 
  fi
fi

echo $interface >/tmp/interface
echo $interface 

$DIALOG --backtitle "$BACKTITLE" --title "Scan or Manual" --menu "\n
Would you like to scan wireless networks with wifi-radar or\n
Input your essid name manually?\n
Which option would you like?" \
14 74 4 \
"Manual" "manually enter essid name" \
"Scan" "scan networks using wifi-radar" \
2> $freply
 result=$?
 [ $result != 0 ] && return $result
reply="`cat $freply`"
case "$reply" in
  Manual)
        sudo /sbin/vwifi2 DISPLAY=$DISPLAY
        exit 0
        ;;
  Scan)
      gksu /usr/sbin/wifi-radar
      exit 0
      ;;
esac
