#!/bin/sh
# wpasupplicant		Starts and stops wpa_supplicant automatically
#
# author: Olaf Conradi <olaf@conradi.name>
#
# 2005-03-01 * Based loosely on ifplugd init.d script
#            * Driver detection taken from hotplugscript
#              by Martijn Pieters <mj@zopatista.com>
#
# TODO:
# * Add Linux 2.6 kernel support for sysfs style detection?
# * Improve madwifi detection to get info from /proc or /sys
# * Add detection for other wpa supported drivers

PATH=/sbin:/bin:/usr/sbin:/usr/bin

DAEMON=/usr/sbin/wpa_supplicant
WPA_CLI=/usr/sbin/wpa_cli
SOCKDIR="/var/run/wpa_supplicant"
CONFIG="/etc/wpa_supplicant.conf"
PNAME="wpa_supplicant"
XARGS=""

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

[ -f $CONFIG ] || ( echo "No configuration file found, not starting."; \
	exit 1; )

[ -f $DAEMON ] || exit 0

set -e

ACTION="$1"
shift

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

# Detect driver of interface first argument
detect_wifi_driver () {
	if [ -d "/proc/net/hostap/$1" ]; then
		DRIVER="hostap"
	elif [ -d "/proc/net/p80211/$1" ]; then
		DRIVER="wext"
	elif [ -d "/proc/net/ndiswrapper/$1" ]; then
		DRIVER="ndiswrapper"
	else
		case "$1" in
			ath*)
				DRIVER="madwifi"
				;;
			*)
				# Unknown
				DRIVER=""
				;;
		esac
	fi
}

[ $# -ne 0 ] && INTERFACES="$@"

if [ "$INTERFACES" = "auto" -o "$INTERFACES" = "all" ]; then
	detect_wifi_interfaces
	XARGS="-w"	# Wait for interface to exist flag
fi

case "$ACTION" in
	start)
		echo -n "Starting wpasupplicant:"
		for IF in $INTERFACES; do
			detect_wifi_driver $IF
			[ "$DRIVER" != "" ] && $DAEMON -c$CONFIG -i$IF -D$DRIVER -B $XARGS && echo -n " $IF"
		done
		echo "."
		;;
	stop)
		echo -n "Stopping wpasupplicant:"
		for IF in $INTERFACES; do
			[ -S "$SOCKDIR/$IF" ] && $WPA_CLI -i$IF terminate > /dev/null
			echo -n " $IF"
		done
		echo "."
		;;
	status)
		for IF in $INTERFACES; do
			[ -S "$SOCKDIR/$IF" ] && $WPA_CLI -i$IF status
		done
		;;
	restart|reload|force-reload)
		$0 stop $INTERFACES
		sleep 3
		$0 start $INTERFACES
		;;
	*)
		echo "Usage: $0 {start|stop|restart|reload|force-reload}" >&2
		exit 1
		;;
esac

exit 0
