#!/bin/bash
### BEGIN INIT INFO
# Provides:          start-wlan
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description:
# Description:
### END INIT INFO

[ -x /sbin/iwconfig ] || exit 0

# Ser LOADWLAN=yes in /etc/default/wlan to start wlan
LOADWLAN=no

[ -f /etc/default/wlan ] && . /etc/default/wlan

find_wlan () {
  INTERFACES=`cat /proc/net/dev | grep : | cut -f1 -d:`
  for IF in $INTERFACES ; do
    iwconfig "$IF" 2>/dev/null | grep -q "^$IF" && echo "$IF"
  done
}

restart_wlan () {
    WLAN="$1"
    /sbin/ifdown "$WLAN"
    # Make sure to close stdin/stdout to avoid hanging on dhclient
    /sbin/ifup "$WLAN" < /dev/null > /dev/null 2>&1 &
}

WLAN=`find_wlan`

case "$1" in 
    start)
        for IFACE in `cat /proc/net/dev | grep : | cut -f1 -d:` ; do 
            if [ "$LOADWLAN" = "yes" ] ; then 
	        # Some drivers support mii-tool, others support ethtool
	        case "`mii-tool $IFACE 2> /dev/null`" in
  	            "$IFACE*link ok")
	            LOADWLAN=no
	            ;;
	        esac
	    fi
        done
	[ -n "$ESSID" ] && /sbin/iwconfig $WLAN ${ESSID+essid $ESSID}
	[ "$LOADWLAN" = "yes" ] && restart_wlan "$WLAN" 
	;;
    stop)
	/sbin/ifdown "$WLAN"
	;;
    status|restart|force-reload)
	;;
    up)
	[ "$2" = "$WLAN" ] || /sbin/ifdown "$WLAN"
	;;
    down)
	[ "$2" = "$WLAN" ] || /sbin/ifup "$WLAN"
	;;
    *)
	echo "Usage: $0 {start|stop|restart|force-reload|status}"
	exit 2
	;;
esac
exit 0
