#!/bin/bash

KEY="/opt/ddns-scripts/keys/Kcompanioncu.be.*.key"
if [ ! -z ${reason} ]; then
	echo "var '\$reason' is set. We got called from dhcpcd.";
	case "$reason" in
	ROUTERADVERT)
		IPV6=$(echo $nd1_addr1 | tr "/" "\n" | head -n 1)
		echo "Updating AAAA record for companioncu.be to $IPV6"
		echo "
			update delete companioncu.be. AAAA
			update delete *.companioncu.be. AAAA
			update add companioncu.be. 10 AAAA $IPV6
			update add *.companioncu.be. 10 AAAA $IPV6
			send
		" | nsupdate -k $KEY
		;;
	DELEGATED6)
	        if [ "${interface}" == "enp4s0" ]; then
			LAN_V6="${delegated_dhcp6_prefix%%/*}"
			WAN_V6="$(ip --json address show dev ppp0 | jq -r '(.[0].addr_info.[] | select(.noprefixroute)).local')"
			#ip6tables -t nat -R public_ip_redirect_to_local 1 -d "${WAN_V6}/128" -j DNAT --to-destination "${LAN_V6}"
		fi
	*)
		echo "$reason not relevant for us. Skipping…"
	esac
else #TODO: come up with some sanity-check for pppd
	# pppd parameters: interface-name tty-device speed local-link-local-address remote-link-local-address ippa‐ram
	IPV4=$4
	echo "Updating A record for companioncu.be to $IPV4"
	echo "
		update delete companioncu.be. A
		update delete *.companioncu.be. A
		update add companioncu.be. 10 A $IPV4
		update add *.companioncu.be. 10 A $IPV4
		send
	" | nsupdate -k $KEY

	# The firewall resolves the domain to allow internal hosts to access forwarded ports.
	# This only happens at startup of iptables. Therefore a restart is only useful if the dns got updated.
	# Otherwise we exit and hope the next forced update will trigger the firewall restart
	NEXT_WAIT_TIME=0
	until [ "$IPV4" = "$(dig companioncu.be A +short)" ]; do
		echo "Query is not what we expected, waiting"
		sleep $(( NEXT_WAIT_TIME++ ))
		if [ $NEXT_WAIT_TIME -eq 10 ]; then
			echo "TIMED OUT! Refusing to restart firewall because dns-query did not update to new ip ($IPV4) but stayed on old…"
			exit 0
		fi
	done
	/etc/init.d/iptables restart
fi