#!/bin/bash

eth0=e1000
ath0=ath_pci
additional="ath_rate_sample ath_hal wlan_scan_sta wlan"
vpn=tun
#additional="wlan_scan_sta ath_rate_sample wlan ath_hal"

# path for wireless tools; should be /sbin unless self compiled version
iwpath=/usr/local/sbin/

ath_present=`/sbin/lsmod | grep -c "$ath0"`
eth_present=`/sbin/lsmod | grep -c "$eth0"`

# variables for WLAN selection
backtitle="WLAN Available"
text="Select the AccessPoint to connect"
listheight=10
width=70
height=17
# wait max. $timeout seconds for selection if none => exit
timeout=10

services="/etc/init.d/cupsys
/etc/init.d/ssh
/etc/init.d/privoxy
/usr/sbin/ddclient
/etc/init.d/fail2ban"

#---- normally, nfs is not required ----
# /etc/init.d/portmap
# /etc/init.d/nfs-common
# /etc/init.d/nfs-kernel-server
#---- normally, nfs is not required ----

#
# Run 'apt-get update' if connected with this IP via eth0
#
updateip=132.187.40.129

stopNetworkServices() {
	for srv in $services
	do
		$srv stop
	done
}

startNetworkServices() {
	for srv in $services
	do
		$srv start
	done
}

setup_ath() {	
	logger -s -t ath0 "Trying to activate ath0..."
	if [ $eth_present != 0 ]; then
		/sbin/ifdown eth0
		/sbin/rmmod $eth0
		/sbin/rmmod $vpn
	fi
	if [ $ath_present == 0 ]; then
		# without strace and all the output
		# the driver is not loaded correctly(????)
		/sbin/modprobe $ath0 
		# > /dev/null 2> /dev/null
		/sbin/modprobe wlan_scan_sta
	fi


	sleep 5

	# /usr/local/bin/wlanconfig ath0 create wlandev wifi0 wlanmode sta
	# configure ath0 as up to be able to use iwlist scan
	/sbin/ifconfig ath0 up

	sleep 10

	logger -s -t ath0 "Interface is up, start scanning"

	tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/wlan$$
	trap "rm -f $tempfile" 0 1 2 5 15

	scan=`$iwpath/iwlist ath0 scan`
	scan=`echo $scan | sed -e 's/Scan completed : //g'`;
	scan=`echo $scan | sed -e 's/: /:/g' | sed -e 's/Bit Rate/BitRate/g' | sed -e 's/Signal level/SignalLevel/g'`;
	scan=`echo $scan | sed -e 's/Encryption key/Encryption/g' | sed -e 's/Noise level/NoiseLevel/g' `;
	scan=`echo $scan | sed -e 's# Mb/s#Mb/s#g' | sed -e 's/ GHz//g' | sed -e 's/dBm//g' | sed -e 's# - # #g' `;
	scan=`echo $scan | sed -e 's#Channel #Ch#g' | sed -e 's#Cell #Cell#g'`;

	# drop the BitRate statements
	short=`echo $scan | sed -e 's#BitRate[:.A-z0-9/]*##g'`;


	# exctract usefull informations for the menue
	j=-1    # temp. cell counter, note that it is incremented by the first AP found!
	for i in $short
	do
		q=`echo $i | grep -c "Cell"`
		if [ $q -gt 0 ]; then
			echo -n "---------- New Cell "
			let j=j+1
			logger -s -t ath0 "---------- New Cell $j ----------"
		fi
		logger -s -t ath0 $i

		q=`echo $i | grep -c "Address"`
		if [ $q -gt 0 ]; then
			addr[$j]=$i
		fi
		q=`echo $i | grep -c "ESSID"`
		if [ $q -gt 0 ]; then
			quotes=`echo $i | grep -c "\"$"`
			if [ $quotes -lt 1 ]; then
				essid[j]="$i..."
			else 
				essid[j]=$i
			fi
		fi
		q=`echo $i | grep -c "Encryption"`
		if [ $q -gt 0 ]; then
			enc[$j]=$i
		fi
		q=`echo $i | grep -c "Quality"`
		if [ $q -gt 0 ]; then
			quality[$j]=$i
		fi
		q=`echo $i | grep -c "NoiseLevel"`
		if [ $q -gt 0 ]; then
			noise[$j]=$i
		fi
	done

	# store the number of access points available
	apcount=$j
	if [ $apcount -gt -1 ]; then
		((apcount++))
		backtitle="$apcount Access Points found"
		# echo "======================================"
		# echo $backtitle
		# drop unnecessary tags
		for (( i=0; i < $apcount; i++ )) do
			essid[$i]=`echo ${essid[$i]} | sed -e 's/ESSID://g'`;
			essid[$i]=`echo ${essid[$i]} | sed -e 's/"//g'`;
			addr[$i]=`echo ${addr[$i]} | sed -e 's/Address://g'`;
			quality[$i]=`echo ${quality[$i]} | sed -e 's/Quality=//g'`;
			noise[$i]=`echo ${noise[$i]} | sed -e 's/NoiseLevel=//g'`;
			enc[$i]=`echo ${enc[$i]} | sed -e 's/Encryption://g'`;
			enc[$i]=`echo ${enc[$i]} | sed -e 's/on/encr/g'`;
			enc[$i]=`echo ${enc[$i]} | sed -e 's/off/open/g'`;
		done 

		# echo "--------------------------------------"
		list=""
		for (( i=0; i < $apcount; i++ )) do
			logger -s -t ath0 "${addr[$i]} Q:${quality[$i]} N:${noise[$i]} --- ${enc[$i]}   ${essid[$i]}"

			list="$list $i ${addr[$i]}___Q:${quality[$i]}/${noise[$i]}___<${enc[$i]}>___${essid[$i]}"
			#'${addr[$i]} - Q:${quality[$i]} N:${noise[$i]} --- ${enc[$i]}'"
		done
		# echo "--------------------------------------"

		dialog --backtitle "$backtitle" --timeout $timeout --menu "$text" $height $width $listheight $list 2> $tempfile

		retval=$?
		choice=`cat $tempfile`

		case $retval in
		  255)
			 logger -s -t ath0 "ESC pressed or timeout, exiting"
			 /sbin/ifdown ath0
			 /sbin/rmmod $ath0
			 /sbin/rmmod $additional
			 /sbin/rmmod $vpn
			;;
		  1)
			 logger -s -t ath0 "Cancel pressed, exiting"
			 /sbin/ifdown ath0
			 /sbin/rmmod $ath0
			 /sbin/rmmod $additional
			 /sbin/rmmod $vpn
			;;
		  0)
			 # Retrieve the full ESSID in case it contained spaces
			 ess=${essid[$choice]}
			 ess=`$iwpath/iwlist ath0 scan | grep -m 1 $ess | cut -d '"' -f 2`
			 logger -s -t ath0 "Selecting network $ess"
			 $iwpath/iwconfig ath0 essid $ess mode managed
			 logger -s -t ath0 "Binding to Access Point ${addr[$choice]}"
			 $iwpath/iwconfig ath0 ap ${addr[$choice]}

			 logger -s -t ath0 "Bringing up interface..."
			 # configure the interface as down first...
	    		 /sbin/ifconfig ath0 down
			 sleep 1
			 # ...for ifup to work correctly!
	    		 /sbin/ifup ath0

			 cp /etc/network/ddclient.ath0 /etc/ddclient.conf
			 # if there is a vpnc-config-file named like the essid,
                         # then fire up vpnc as it is required for this lan
			 if [ -e "/etc/vpnc/$ess.conf" ]; then
			 	logger -s -t ath0 "Login in to VPN"
				/usr/sbin/vpnc-connect $ess
				# bind ddclient to the virtual interface
			 	cp /etc/network/ddclient.tun0 /etc/ddclient.conf
			 fi

			 startNetworkServices

			 # Setup the firewall and network services
			 if [ -e /etc/init.d/fail2ban ]; then
			         /etc/init.d/fail2ban start
			 fi
			 ;;
		esac
	else 
		logger -s -t ath0  "No Access Point available/ready. Disabeling WLAN, removing modules"
		/sbin/ifdown ath0
		/sbin/rmmod $ath0
		/sbin/rmmod $additional
		/sbin/rmmod $vpn
	fi


# --------------------------------------------------------

	ath_present=`/sbin/lsmod | grep -c "$ath0"`
	if [ $ath_present -gt 0 ]; then
		logger -s  -t ath0 "Driver loaded, WLAN activated and configured."
	fi
}

setup_eth() {
	logger -s -t eth0 "Trying to activate eth0..."
   	if [ $ath_present != 0 ]; then
		/sbin/ifdown ath0
		/sbin/rmmod $ath0
		/sbin/rmmod $additional
		/sbin/rmmod $vpn
	fi
	if [ $eth_present == 0 ]; then
		/sbin/modprobe $eth0
	fi

	# Sleep a second for things to settle...
	sleep 3

	# check for a link
	link=`/sbin/mii-tool eth0 | grep -c "no link"`
	if [ $link == 0 ]; then
		/sbin/ifup eth0
		if [ -e /etc/init.d/fail2ban ]; then
		        /etc/init.d/fail2ban start
		fi
		cp /etc/network/ddclient.eth0 /etc/ddclient.conf
		/usr/sbin/ddclient &
	else
		logger -s -t eth0 "No link or cable, disabeling LAN, removing modules"
		/sbin/rmmod $eth0
	fi
	#
	# Check if updates should be processed
	#
	updatepackages=`/sbin/ifconfig | grep eth0 -A 2 | grep $updateip -c`
	if [ $updatepackages == 1 ]; then
		logger -s -t LAN "Searching for system upgrades..."
		# /usr/bin/apt-get update > /dev/null 2> /dev/null 
		# /usr/bin/apt-get update > /dev/null 2> /dev/null
		# /usr/bin/apt-get -s upgrade | mail arwagner -s "[Debian] Available Upgrades"
	fi
	eth_present=`/sbin/lsmod | grep -c "$eth0"`
	if [ $eth_present -gt 0 ]; then
		logger -s -t eth0 "eth0 loaded, LAN activated and configured."
		startNetworkServices
	fi
}

setup_off() {
	if [ $ath_present != 0 ]; then
		/sbin/ifdown ath0
		/sbin/rmmod $ath0
		/sbin/rmmod $additional
		/sbin/rmmod $vpn
		logger -s -t LAN "ath0 shut down, modules removed."
	fi
	if [ $eth_present != 0 ]; then
		/sbin/ifdown eth0
		/sbin/rmmod e1000
		/sbin/rmmod $vpn
		logger -s -t LAN "eth0 shut down, modules removed."
	fi
}

stopNetworkServices

case $1 in
   #
   # Configure ath0 only mode
   #
   --ath0)
   	setup_ath
	;;
   #
   # Configure eth0 only mode
   #
   --eth0)
   	setup_eth
	;;
   #
   # Configure no networking
   #
   --off)
   	setup_off
	;;
   #
   # Configure eth0 or ath0, whatever is possible
   #
   *)
   	logger -s -t LAN "Searching for LAN connections, autoconfiguring..."
   	setup_eth
	if [ $eth_present == 0 ]; then
		setup_ath
	fi
   	;;
esac
   	
