#!/bin/sh
# hotplug agent script

# author: Olaf Conradi <olaf@conradi.name>
#
# 2005-03-02 * Initial version
#            * Based on my modified version of ifplugd.hotplug
#

DAEMON_NAME=wpasupplicant

DAEMON=/usr/sbin/wpa_supplicant
CFG=/etc/default/$DAEMON_NAME

[ -x $DAEMON ] || exit 0

HOTPLUGFUNCS=/etc/hotplug/hotplug.functions
[ -f $HOTPLUGFUNCS ] || exit 1
. $HOTPLUGFUNCS
DEBUG=yes export DEBUG

# Get list of wireless interfaces
detect_wifi_interfaces () {
	if [ -r /proc/net/wireless ]; then
		HOTPLUG_INTERFACES=$(cat /proc/net/wireless | awk 'sub(":","") {print $1}')
	else
	# Nothing found, clear interfaces
		HOTPLUG_INTERFACES=""
	fi
}

# return true (0) if interface from list $1 is in list $2
# return false (1) otherwise
search_interfaces () {
        for IF in $2 ; do
                for SEARCH_IF in $1 ; do
                        if [ "$SEARCH_IF" = "$IF" ] ; then
                                return 0
                        fi
                done
        done
        return 1
}

[ "$INTERFACE" ] || { mesg Bad invocation: \$INTERFACE is not set ; exit 1 ; }

[ -f $CFG ] || { mesg No $DAEMON_NAME configuration file ; exit 1 ; }
. $CFG

# Replace "all" or "auto" with list of current wireless interfaces
[ "$HOTPLUG_INTERFACES" = "auto" -o "$HOTPLUG_INTERFACES" = "all" ] && detect_wifi_interfaces

case $ACTION in
add|register)
	search_interfaces "$INTERFACE" "$INTERFACES"
	if [ $? -gt 0 ] ; then
		# Interface isn't statically managed by wpasupplicant
		search_interfaces "$INTERFACE" "$HOTPLUG_INTERFACES"
		if [ $? -eq 0 ] ; then
			# Interface is in hotplug allowed list,
			# start wpasupplicant
			debug_mesg Invoking $DAEMON_NAME for $INTERFACE
			/etc/init.d/$DAEMON_NAME start $INTERFACE
		fi
	fi
	;;
remove|unregister)
	debug_mesg Stopping $DAEMON_NAME for $INTERFACE
	/etc/init.d/$DAEMON_NAME stop $INTERFACE
	;;
esac
