#!/bin/sh

DEFAULT_RUNDIR=$(uci get resolver.kresd.rundir)
TMP_HINTS_CONFIG=$DEFAULT_RUNDIR/hints.tmp			#generated by kresd
TMP_HINTS_CONFIG_EMPTY=$DEFAULT_RUNDIR/hints_empty.tmp		#empty file to clear hints
TMP_HINTS_CONFIG_DYNAMIC=$DEFAULT_RUNDIR/hints_dynamic.tmp

TTY_PATH=$DEFAULT_RUNDIR/tty/$(pidof kresd)
LOCAL_DOMAIN=$(uci get dhcp.@dnsmasq[0].local| sed 's|/||g')
DHCP_LEASES=/tmp/dhcp.leases

add_dhcp_record() {
	local mac=$1
	local ipv4=$2
	if [[ ! -z "$ipv4" ]]; then
		echo "$DNSMASQ_LEASE_EXPIRES $mac $ipv4 $DNSMASQ_SUPPLIED_HOSTNAME $DNSMASQ_CLIENT_ID">>$DHCP_LEASES
		sort -u $DHCP_LEASES>$DHCP_LEASES.tmp
		cat $DHCP_LEASES.tmp | sed '/^\s*$/d' > $DHCP_LEASES
		rm $DHCP_LEASES.tmp
	fi
}

del_dhcp_record() {
	local mac=$1
	local ipv4=$2

	if [[ ! -z "$DNSMASQ_CLIENT_ID" ]]; then
		cat $DHCP_LEASES | grep -v "$DNSMASQ_CLIENT_ID" >$DHCP_LEASES.tmp
		mv -f $DHCP_LEASES.tmp $DHCP_LEASES
	fi
}

dhcp_record() {
	local mac=$1
	local ipv4=$2
	local op=$3

	if [[ -z "$DNSMASQ_SUPPLIED_HOSTNAME" ]]; then
		DNSMASQ_SUPPLIED_HOSTNAME='*'
	fi

	if [[ -z "$DNSMASQ_CLIENT_ID" ]]; then
		DNSMASQ_CLIENT_ID='*'
	fi

	if [ "$op" == "add" ]; then
		add_dhcp_record $mac $ipv4
	fi

	if [ "$op" == "del" ]; then
		del_dhcp_record $mac $ipv4
	fi

	if [ "$op" == "old" ]; then
		del_dhcp_record $mac $ipv4
		add_dhcp_record $mac $ipv4
	fi

}

clear_hints() { #clear all hints record from kresd
	echo "">$TMP_HINTS_CONFIG_EMPTY
	echo "hints.config('$TMP_HINTS_CONFIG_EMPTY')" | socat - UNIX-CONNECT:$TTY_PATH > /dev/null 2>&1
}

load_dynamic_hints() {

	#init dynamic hints file
	echo "#Do not edit">$TMP_HINTS_CONFIG_DYNAMIC
	echo "#file generated from $TMP_HINTS_CONFIG and $DHCP_LEASES ">>$TMP_HINTS_CONFIG_DYNAMIC

	#copy static hints
	cat $TMP_HINTS_CONFIG>>$TMP_HINTS_CONFIG_DYNAMIC

	#add dhcp dynamic domains
	while read line; do
		ip=$(echo "$line"|awk '{print $3}')
		name=$(echo "$line"|awk '{print $4}')
		if [ "$name" != '*' ]; then
			echo $ip $name.$LOCAL_DOMAIN>>$TMP_HINTS_CONFIG_DYNAMIC
		fi
	done <$DHCP_LEASES

	#load generated hints file
	echo "hints.config('$TMP_HINTS_CONFIG_DYNAMIC')" | socat - UNIX-CONNECT:$TTY_PATH  > /dev/null 2>&1
}


arg_mac=$2
arg_ipv4=$3
arg_op=$1

prefered_resolver=$(uci get resolver.common.prefered_resolver)
enable_dynamic_domains=$(uci get resolver.kresd.dynamic_domains)

dhcp_record $arg_mac $arg_ipv4 $arg_op

if [ "$prefered_resolver" == "kresd" ] && [ "$enable_dynamic_domains" == "1" ]; then
	clear_hints
	load_dynamic_hints
fi

