#!/bin/sh

## wpa-ifupdown init script.

## Callum Dickinson <gcfreak_ag20@hotmail.com>
## Sonic Team Junior <http://www.srb2.org>
## http://mb.srb2.org/showthread.php?t=31137
## svn://code.srb2.org/SRB2/branches/WII

## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.


#--------------------#
. /lib/lsb/init-functions
. /etc/profile
LOGFILE="$LOGDIR/$ME.log"
#--------------------#

test -d /var/run || exit 0

test -x /sbin/ifdown || exit 0

stop_wpa_action () {
	test -x /sbin/wpa_action || return 0
	IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_action.*.pid' -printf '%P\n' | \
		cut -d'.' -f2 2>/dev/null)
	if test -n "$IFACES"; then
		log_daemon_msg "Stopping wpa_action roaming interfaces"
		for iface in $IFACES; do
			log_progress_msg "$iface"
			# wpa_action executes /sbin/ifdown
			wpa_action "$iface" stop >/dev/null 2>&1
		done
		log_end_msg 0
	fi
}

stop_wpa_supplicant () {
	IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_supplicant.*.pid' -printf '%P\n' | \
		grep -v wpa_supplicant.dbus.pid | cut -d'.' -f2 2>/dev/null)
	if test -n "$IFACES"; then
		log_daemon_msg "Stopping wpa_supplicant interfaces"
		for iface in $IFACES; do
			log_progress_msg "$iface"
			ifdown "$iface" >/dev/null 2>&1
		done
		log_end_msg 0
	fi
}

sendsigs_omission_support () {
	if [ -d /lib/init/rw/sendsigs.omit.d/ ]; then
		# Debian
		return 0
	elif [ -d /var/run/sendsigs.omit.d/ ]; then
		# Ubuntu, cf. https://bugs.launchpad.net/bugs/181541
		return 0
	fi

	return 1
}

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

exit 0
