#!/bin/bash

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

[ -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 
}

WLAN=`find_wlan`

case "$1" in 
    start)
	LOADWLAN=yes
	for IFACE in `cat /proc/net/dev | grep : | cut -f1 -d:` ; do 
	    # Some drivers support mii-tool, others support ethtool
	    case "`mii-tool $IFACE 2> /dev/null`" in
		"$IFACE*link ok")
		    LOADWLAN=no
		    ;;
	    esac
	done
	[ -n "$ESSID" ] && /sbin/iwconfig $WLAN ${ESSID+essid $ESSID}
	[ "$LOADWLAN" = "yes" ] && /sbin/ifup "$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
