#!/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.

G_DHCPCD=/etc/dhcpcd.conf 
I_DHCPCD=/tmp/wpa_gui-wired-dhcpcd.$1.conf
PIDFILE=/tmp/wpa_gui-wired-dhcpcd.$1.pid
LOCKFILE=/tmp/wpa_gui-wired.$1.lock
MAC=$(cat /sys/class/net/$1/address)

# helper - kill wpagui-initiated dhcpcd
kill_dhcpcd() {
	if [ -f $PIDFILE ]; then
		read pid < $PIDFILE
		kill $pid; sleep 1; kill -0 $pid && kill -9 $pid
		rm -f $PIDFILE
	fi
}

#Main
[ -e $LOCKFILE ] && exit #Exit if already running 
touch $LOCKFILE
kill_dhcpcd # 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 [ -e "$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
			cat /var/run/dhcpcd-$1.pid > $PIDFILE
fi
rm $LOCKFILE
