#! /bin/sh
# DHCP server lease notify script so that it can trigger start WFD.
# This script is called by DHCP server either when it acknowledges DHCP Reqeust,
# or anytime when it receives SIGUSR1.
#
# Usage: udhcpd-notify <lease_file> [latest_leased_IP]

IP=$2
IPFILE=/tmp/app/p2p-source-ip
WFDIPFILE=/tmp/app/wfd-source-ip
WFD_DEV_FILE=/tmp/wfd-device  # match in supplicant
P2P_DHCP_WAIT_FILE=/tmp/app/p2p-dhcp-wait
PERSIST=/nvram/udhcpd-p2p.leases

# Assume the latest leased IP belongs to the P2P connected peer.
# This requires DHCP server code changes to provide it.
# Note: this also assumes DHCP server only serves us alone

echo === udhcpd-notify starts >> /tmp/udhcpd.log
if [ ! -z $IP ]; then
	if dumpleases -f $1 | grep ${IP}; then
		# trigger killing of previous paired
		if [ -f ${WFDIPFILE} ]; then
			# rm -f ${IPFILE}
			echo `date` Not Delete ${WFDIPFILE} >> /tmp/udhcpd.log
			echo `date` `cat ${WFDIPFILE}` >> /tmp/udhcpd.log
			sleep 1
		fi
		while [ -f ${P2P_DHCP_WAIT_FILE} ]; do
			sleep 1
		done
		echo `date` Write IP: ${IP} to ${WFDIPFILE} >> /tmp/udhcpd.log
		echo ${IP} > ${IPFILE}

		dumpleases -f $1 | awk '$2 == "'"${IP}"'" { print "udhcpd lease:", $1, $2 }' > /tmp/p2papp_log.fifo

		# If the mac address for the IP has changed, persist the leases file to /nvram
		OLDINFO=`dumpleases -f ${PERSIST} | awk '$2 == "'"${IP}"'" { print $1, $2 }`
		NEWINFO=`dumpleases -f $1         | awk '$2 == "'"${IP}"'" { print $1, $2 }`
		if [ "${NEWINFO}" != "${OLDINFO}" ]; then
			cp $1 ${PERSIST}
			echo New udhcpd pairing for ${IP}, persisted data > /tmp/p2papp_log.fifo
		fi

		MACADDR=`dumpleases -f $1 | grep "${IP}" | cut -d " " -f 1`
		if grep "${MACADDR}" ${WFD_DEV_FILE}; then
			echo ${IP} > ${WFDIPFILE}
		fi
	else
		echo $0 ${IP} has not been leased
	fi
else
	echo $0 no lease

	# This was a recurring udpate. If data has changed, persist to /nvram
	if ! cmp -s $1 ${PERSIST}; then
		cp $1 ${PERSIST}
		echo persisted udhcpd data > /tmp/p2papp_log.fifo
	fi
fi
