#!/bin/bash
#set -e
#set -x

#	DHCP commit/release/expiry status drives this process

####################	following 11 lines just for testing  ####################
/usr/bin/logger --tag dhcp1 "testing --> $0 (v15)"
#	Kill the unbound-dhcp-leases-bridge process
pgrep -f unbound-dhcp-leases-bridge &&
	kill -s SIGTERM $(pgrep -d',' -f unbound-dhcp-leases-bridge) &&
	/usr/bin/logger --tag dhcp1 "terminated unbound-dhcp-leases-bridge"

#	if no dhcpLeases then create file
#[[ -f "${unboundDHCPleases}" ]] || touch "${unboundDHCPleases}"

#	chmod -v 744 /root/dhcpdconf/dhcpEvent_vN.sh
#	ln -vsf /root/dhcpdconf/dhcpEvent_vN.sh /root/dhcpdconf/dhcpEvent.sh
#-------------------------------------------------------------------------------


#	need DOMAINNAME value
eval $(/usr/local/bin/readhash /var/ipfire/main/settings)

dhcpCREstatus=$1
clientIP=$2
clientName=$3

unboundDHCPleases="/etc/unbound/dhcp-leases.conf"				#	output to unbound
unboundStaticHosts="/etc/unbound/hosts.conf"

TTL="60"														#	time to live (seconds)

#	add domain name to client name
clientFQDN=$( echo "${clientName}.${DOMAINNAME}"  )		#	 | tr '[:upper:]' '[:lower:]'

#	reverse IP
reverseIP=$( echo "${clientIP}" | awk -F. '{print $4"."$3"."$2"."$1}' )
arpaName=$( echo "${reverseIP}.in-addr.arpa" )

#	create "A" record and "PTR" record for unbound
#	made "absolute address" by adding a "." at the end of names
#	this is done for consistency with the unbound cache
aRecord="${clientFQDN}. ${TTL} IN A ${clientIP}"
ptrRecord="${arpaName}. ${TTL} IN PTR ${clientFQDN}."

#	create local data line using above Records
aRecordLD="local-data: \"${aRecord}"\"
ptrRecordLD="local-data: \"${ptrRecord}"\"

case "${dhcpCREstatus}" in
	commit)
		#	if client name is blank then exit
		[[ -z "${clientName}" ]] &&
			{ /usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: no clientName - exit" ; exit ; }

		#	if client exists in static hosts then exit
		if grep --word-regexp --quiet -e "${clientIP}" -e "${clientName}" "${unboundStaticHosts}" ; then
			/usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: ${clientName} or ${clientIP} found in static hosts - exit"
			exit
		fi

		#	does A record and PTR record already exist? if no, then add
		if ! grep --word-regexp --quiet -e "${clientIP}" -e "${reverseIP}" "${unboundDHCPleases}" ; then
			#	add A record and PTR record to unbound
			echo -e "${aRecordLD}\n${ptrRecordLD}" >> "${unboundDHCPleases}"
			echo -e "${aRecord}\n${ptrRecord}" | /usr/sbin/unbound-control local_datas

			/usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: Record A and PTR added to unbound"
		else
			/usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: Record A and PTR already exist"
		fi
		;;

	release|expiry)
		#	"expiry" and "release" are the same since I don't understand the difference    :-(

		#	does IP addr or Reverse IP appear in unbound dhcp-leases file?  if yes, delete line
		if grep --word-regexp --quiet -e "${clientIP}" -e "${reverseIP}" "${unboundDHCPleases}" ; then
			#	Since expiry does not return names, we must use the IP addr to find two FQDNs.
			#	get FQDN by searching for IP address
			uc_FQDN=$( unbound-control list_local_data | grep --word-regexp "${clientIP}" | awk '{ print $1 }' )
			[[ -z "${uc_FQDN}" ]] &&
				{ /usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: Oops - no uc_FQDN - exit" ; exit ; }
				
			#	remove FQDNs from unbound dhcp-leases file (two lines in file)
			/bin/sed --in-place "/${uc_FQDN}/d" "${unboundDHCPleases}"
			/usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: ${uc_FQDN} removed from ub dhcp leases"

			#	Since "local_data_remove" uses only names to delete (Client Name and arpa Name),
			#		we must get both names by searching for FQDN (returns two lines).
			#		e.g., "iMac3.localdomain."  AND  "100.6.168.192.in-addr.arpa."
			uc_Names=$( unbound-control list_local_data | awk "/${uc_FQDN}/" | awk '{ print $1 }' )

			#	for unbound cache, MUST be deleted by name for A record and arpa name for PTR record!
			echo -e "${uc_Names}" | /usr/sbin/unbound-control local_datas_remove

			/usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: ${uc_Names} removed from unbound-control"
		else
			/usr/bin/logger --tag dhcp1 "${dhcpCREstatus}: ${clientIP} or ${reverseIP} not found"
		fi
		;;

	*)
		/usr/bin/logger --tag dhcp1 "CRE script: case = no status"
		echo "Usage:  dhcpEvent <status> <ip_address> <client_hostname>"
		exit
		;;
esac

exit