From d811e15f36b3a4c7b5b87660d1998617d73578bc Mon Sep 17 00:00:00 2001
From: tim <tim@treehouse.org.za>
Date: Wed, 5 Mar 2025 10:32:14 +0200
Subject: [PATCH] Update nsupdate script to be more discerning about IP
 addresses

---
 update_ip.sh | 33 ++++++++++++++++++++++++++-------
 1 file changed, 26 insertions(+), 7 deletions(-)

diff --git a/update_ip.sh b/update_ip.sh
index 11befec..199f5db 100755
--- a/update_ip.sh
+++ b/update_ip.sh
@@ -5,15 +5,34 @@ server=ns1.example.com
 zone=dyn.example.com
 host=desktop
 secret=""
-iface=eth0
+iface=$( ip route get $( dig +short ${server} | grep [0-9] ) | grep -Po '(?<=(dev ))(\S+)' )
 
+# TODO trigger not via cron, but using ip monitor in a while/sleep loop:
+#ip monitor address dev ${iface} | while read event; do
+#    case "$event" in
+#    'Deleted default'*)
+#        ...
+#        ;;
+#    'local '*)
+#        ...
+#        ;;
+#    ...)
+#        ...
+#        ;;
+#    ...
+#    esac
+#done
+
+# This has to be retrieved externally
 new_ip4=$( wget -4 -q -O - https://treehouse.org.za/ip )
-new_ip6=$( ip -6 addr show ${iface} | grep global | grep -oP '(?<=inet6\s)[\da-f:]+' )
+# If the iface call fails, we will get several interfaces, so pipe through head to get the first (default) interface
+new_ip6=$( ip -6 addr show ${iface} scope global | grep -vE '(mngtmpaddr|deprecated)' | grep -oP '(?<=inet6\s)[\da-f:]+' | grep -vE '^fc' | head -1 )
 
-cur_ip4=$( nslookup -type=a ${host}.${zone} | grep -oP '(?<=^Address:\ )\d+(\.\d+){3}$' )
-cur_ip6=$( nslookup -type=aaaa ${host}.${zone} | grep -oP '(?<=^Address:\ )[\da-f:]+$' )
+cur_ip4=$( nslookup -type=a ${host}.${zone} | grep -oP '(?<=^Address:\ )\d+(\.\d+){3}$' | head -1 )
+cur_ip6=$( nslookup -type=aaaa ${host}.${zone} | grep -oP '(?<=^Address:\ )[\da-f:]+$' | head -1 )
 
-if [ -z ${new_ip4} ] && [ -z ${new_ip6} ]; then
+#if [ -z ${new_ip4} ] && [ -z ${new_ip6} ]; then
+if [ -z ${new_ip4} ]; then
         exit;
 fi
 
@@ -46,12 +65,12 @@ else
 fi
 
 ipv6_line=""
-if [ -n "${new_ip6}" ]; then
+if [ -n "${new_ip6}" ] && [ "${cur_ip6}" != "${new_ip6}" ]; then
     ipv6_line="update add ${host}.${zone}. 60 AAAA ${new_ip6}"
 fi
 
 update=$( cat <<-EOF
-        server ${server}
+        server ${server}.
         zone ${zone}.
         key ${host}.${zone} ${secret}
         update delete ${host}.${zone}.