#!/bin/dash
#Called by wpa_cli daemon. Wpa_cli is executed like this 'wpa_cli -a dhcpcd-wpagui'.
#Wpa_cli calls dhcpcd-wpagui with: $1 is the interface (eth0, ath0, etc),
#and $2 is the event - either "CONNECTED" or "DISCONNECTED".

#exec >>/tmp/${0##*/}.log 2>&1
#echo ========================
#date +%Y%m%d-%H%M%S
#echo "$0 $*"
#echo ========================
#set -x

G_DHCPCD=/etc/dhcpcd.conf
I_DHCPCD=/tmp/wpa_gui-wired-dhcpcd.$1.conf
TIMEOUT=120	# in seconds

# helper - kill wpagui-initiated dhcpcd
kill_dhcpcd() {
	local i=0 pid
	if [ -s /var/run/dhcpcd-$1.pid ] &&
		read pid < /var/run/dhcpcd-$1.pid &&
		[ "$pid" ]
	then
		while [ -s /var/run/dhcpcd-$1.pid -a $i -lt 15 ]; do
			kill $pid; sleep 1
			kill -0 $pid || return
			i=$(($i+1))
		done
		kill -9 $pid 2> /dev/null
		# should this process become a zombie it won't take up any
		# resources other than its process pid
	fi
}

### main
kill_dhcpcd $1 # always kill previous wpagui-initiated dhcpcd
ip addr flush dev $1 # always remove existing ip address
SSID="$(wpa_cli status | grep ssid | grep -v bssid | cut -d "=" -f 2)"
STATICFILE="/etc/wpa_gui/wifi/$SSID"
unset IPADDRESS SUBNET GATEWAY DNS1 DNS2
if [ -f "$STATICFILE" ]; then
	unset x; read x < "$STATICFILE"
	IPADDRESS="${x%%|*}"; x="${x#*|}"
	SUBNET="${x%%|*}"; x="${x#*|}"
	GATEWAY="${x%%|*}"; x="${x#*|}"
	DNS1="${x%%|*}"; x="${x#*|}"
	DNS2="${x%%|*}"; x="${x#*|}"
fi

if [ "$IPADDRESS" ] ; then

# Static

	cp $G_DHCPCD $I_DHCPCD &&
	# Do not quote values. This isn't a shell file. Cf. resolv.conf(5).
	echo "
	interface $1
		static ip_address=$IPADDRESS
		static subnet=$SUBNET
		static routers=$GATEWAY
		static domain_name_servers=$DNS1 $DNS2
		" >> $I_DHCPCD #
	dhcpcd -f $I_DHCPCD $1 &&
	dhcpcd -x $1 # signal the above process to exit
	rm -f $I_DHCPCD

else

#DHCP
	case "$2" in
		CONNECTED)
			#dhcpcd -q -t $TIMEOUT -L -h $(hostname) $1 # timeout, no ipv4ll, pass hostname to dhcp server
			dhcpcd -q -b -L -h $(hostname) $1 # background immediately, no ipv4ll, pass hostname to dhcp server
			;;

		DISCONNECTED)
			;;
	esac

fi
