#!/bin/sh

grep -q "^wl" /proc/modules||exit

if [ -z `pidof olsrd` ]; then
	reboot
fi

eval `/etc/wl status|sed -e "s/.*Channel: /wlchannel=/;s/BSSID: /wlbssid=/;s/	.*//"|sed -n -e "2p;3p"`

if [ -n "$wlchannel" ] && [ -n "$wlbssid" ]; then
	eval `grep channel= /etc/system.conf`
	eval `grep ff_bssid= /etc/system.conf`
	if [ -n "$channel" ] && [ $channel != $wlchannel ]; then
		# Wrong Channel, wait a minute
		wl down
	elif [ -n "$ff_bssid" ] && [ $ff_bssid != $wlbssid ]; then
		# Wrong BSSID, wait a minute
		wl down
	fi
else
	# Wifi down: Try to restart
	wl up
	sleep 5
	eval `/etc/wl status|sed -e "s/.*Channel: /wlchannel=/;s/BSSID: /wlbssid=/;s/	.*//"|sed -n -e "2p;3p"`
	if [ -z "$wlchannel" ] || [ -z "$wlbssid" ]; then
		# Still not up
		reboot
	elif [ -n "$channel" ] && [ $channel != $wlchannel ]; then
		# Still wrong Channel
		reboot
	elif [ -n "$ff_bssid" ] && [ $ff_bssid != $wlbssid ]; then
		# Still wrong BSSID
		reboot
	fi
fi
