#!/bin/sh
# ifupdown hook script for enhanced MadWifi (madwifi-ng) support in
# Debian and Debian-based distributions
#
# $Id: madwifi 29 2006-09-27 05:48:07Z mrenzmann $
#
# Copyright (c) 2006 Michael Renzmann <mrenzmann@otaku42.de>
# Portions Copyright (c) 2005 Matt Brown <matt@mattb.net.nz>
#
# For further information see:
# http://projects.otaku42.de/wiki/madwifi-ifupdown
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 2 as published by the Free
# Software Foundation.
#
# This 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.
#
# You should have received a copy of the GNU General Public License along with
# the madwifi-ifupdown package; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
LIBDIR=@LIBDIR@
if [ ! -d "$LIBDIR" ]; then
	echo "ERROR: $LIBDIR: no such directory"
	exit 1
fi

if [ ! -f $LIBDIR/defaults ]; then
	echo "ERROR: $LIBDIR/defaults: no such file"
	exit 1
fi
. $LIBDIR/defaults

if [ ! -f "$LIBDIR/functions.inc.sh" ]; then
	echo "ERROR: unable to load functions.inc.sh" >&2
	exit 1
fi
. $LIBDIR/functions.inc.sh


[ -x "$HOSTAPD" ] || exit 0
[ -n "$IF_ATH_PARENT" ] || exit 0

if [ "$VERBOSITY" -eq "0" ]; then
	exec 1>/dev/null
fi

IF_ATH_VAPTYPE=$(echo "$IF_ATH_VAPTYPE" | tr [A-Z] [a-z])
if [ -n "$IF_ATH_VAPTYPE" ]; then
	case "$IF_ATH_VAPTYPE" in
	ap|master)
		VAPTYPE=ap
	;;
	*)
		VAPTYPE=other
	;;
	esac
# else use default from $LIBDIR/defaults
fi

IF_ATH_SECURITY=$(echo "$IF_ATH_SECURITY" | tr [A-Z] [a-z])
if [ -n "$IF_ATH_SECURITY" ]; then
	case "$IF_ATH_SECURITY" in
	wpa1and2|wpa2|wpa1|wpa)
		SECURITY=wpa
	;;
	*)
		SECURITY=other
	;;
	esac
# else use default from $LIBDIR/defaults
fi

# stop hostapd for this interface
if [ "$VAPTYPE" = "ap" ] && [ "$SECURITY" = "wpa" ]; then
	HOSTAPD_CFGFILE="$HOSTAPD_CFGDIR/hostapd-$IFACE.conf"
	proc="$HOSTAPD -B $HOSTAPD_CFGFILE"
	count=0
	while [ -n "$(ps x | grep "$proc")" ]; do
		(( count++ ))
	
		if [ $count -gt 5 ]; then
			error "failed to stop hostapd after 5 tries, giving up"
		fi
		if [ $count -ge 2 ]; then
			warning "stopping hostapd, try #$count"
		fi
	
		pid="$(ps x | grep "$proc" | cut -b1-5)"
		if [ -n "$pid" ]; then
			kill "$pid"
			sleep 1
		else
			warning "$IFACE: WPA selected, but no hostapd running?"
		fi
	done

	if [ -f "$HOSTAPD_CFGFILE" ]; then
		rm -f "$HOSTAPD_CFGFILE"
	fi
fi

# that's all, folks!
exit 0
