#!/bin/dash

#Called by wpa_gui patched for wired connections. $1 = interface.
#Called by both Connect and Disconnect buttons.
#Also called by /etc/init.d/50-Wpagui directly.

#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
LOCKFILE=/tmp/wpa_gui-wired.$1.lock
read MAC < /sys/class/net/$1/address

# 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
[ -e $LOCKFILE ] && exit #Exit if already running
touch $LOCKFILE
kill_dhcpcd "$1" # always kill previous wpagui-initiated dhcpcd
ip addr flush dev $1 # always remove existing ip address

# wpa_gui names the static conf file by mac address or interface name.
CONFIGFILE=$1
[ -e /etc/wpa_gui/wired/mac-$1 ] && CONFIGFILE=$MAC
if [ -e /etc/wpa_gui/wired/$CONFIGFILE-down ] ; then #If wap_gui has set the down flag then exit.
rm $LOCKFILE
exit
fi

STATICFILE="/etc/wpa_gui/wired/$CONFIGFILE"
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 "
	hostname $(hostname)
	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
			dhcpcd -q -b -L -h $(hostname) $1 # background immediately, no ipv4ll, pass hostname to dhcp server
fi
rm $LOCKFILE
