#!/bin/sh

### BEGIN INIT INFO
# Provides:		wpa-ifupdown
# Required-Start:	$network
# Required-Stop:	$network
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop:		0 6
# Short-Description:	Stop wpa_supplicant processes started via ifupdown
# Description:		Run ifdown on interfaces authenticated via
#			wpa_supplicant.	Sendsigs terminates wpa_supplicant
#			processes before networking is stopped causing each
#			network interface authenticated via a wpa_supplicant
#			daemon to be terminated abrubtly.
### END INIT INFO

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

test -d /var/run || exit 0

test -x /sbin/ifdown || exit 0

if test -e /etc/network/run/ifstate; then
	IFSTATE_FILE="/etc/network/run/ifstate"
elif test -e /var/run/network/ifstate; then
	IFSTATE_FILE="/var/run/network/ifstate"
else
	exit 0
fi

. /lib/lsb/init-functions

stop_wpa_action () {
	test -x /sbin/wpa_action || return
	local iface
	for iface in $(find /var/run -maxdepth 1 -type f -name 'wpa_action.*.pid' -printf '%P\n' | cut -d'.' -f2); do
		log_action_begin_msg "Stopping wpa_action roaming interface $iface"
		# wpa_action executes /sbin/ifdown
		/sbin/wpa_action $iface stop >/dev/null 2>&1
		if [ "$?" -eq 0 ]; then
			log_action_end_msg "$?"
		else
			log_action_end_msg "$?" "logged to /var/log/wpa_action.log"
		fi
	done
}

stop_wpa_supplicant () {
	local iface
	for iface in $(find /var/run -maxdepth 1 -type f -name 'wpa_supplicant.*.pid' -printf '%P\n' | cut -d'.' -f2); do
		if grep --quiet --no-messages "^$iface" "$IFSTATE_FILE"; then
			log_action_begin_msg "Stopping wpa_supplicant interface $iface"
			/sbin/ifdown $iface >/dev/null 2>&1
			log_action_end_msg "$?"
		fi
	done
}

case "$1" in
	start|restart|force-reload)
		# No-op
		;;
	stop)
		stop_wpa_action
		stop_wpa_supplicant
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 3
		;;
esac

exit 0
