#!/bin/sh

if [ -z "$1" -o -z "$2" ]; then
	echo "Insufficient parameters" > /dev/stderr
	exit 1
fi

IFACE="$1"
ACTION="$2"
WPA_CLI_ACTFILE="/var/run/wpa_cli.$IFACE.action"

DHCP_BIN="/sbin/dhclient"
DHCP_PID="/var/run/dhclient.$IFACE.pid"
DHCP_LEASES="/var/run/dhclient.$IFACE.leases"


case "$ACTION" in

	CONNECTED)
		if [ ! -e "$WPA_CLI_ACTFILE" ]; then
			$DHCP_BIN -pf $DHCP_PID -lf $DHCP_LEASES $IFACE
			# Just incase, touch the pidfile
			touch $DHCP_PID
		fi
		touch $WPA_CLI_ACTFILE
		;;

	DISCONNECTED)
		if [ -e "$WPA_CLI_ACTFILE" ]; then
			$DHCP_BIN -r $IFACE
			pkill -f "$DHCP_BIN -pf $DHCP_PID -lf $DHCP_LEASES $IFACE"
			rm -f $DHCP_PID
		fi
		rm -f $WPA_CLI_ACTFILE
		;;

	*)
		echo "Unknown action" > /dev/stderr
		exit 1
		;;

esac
