#!/bin/sh
# test/parse_servers.sh
#
# CI guard: verify the authority parse/rebuild in ddns_url_lib.sh works on
# EVERY shipped provider preset. A new preset with an unparseable authority
# (or a regression in the lib) fails the build.
#
# Checks per ipv4/ipv6 url:
#   1. parse succeeds (or the url is a known script-based provider -> logged)
#   2. round-trip: rebuild with no overrides reproduces the url (modulo
#      default-port normalization)
# Plus a fixed set of override spot-checks.

cd "$(dirname "$0")/.." || exit 2
. files/ddns-script/usr/lib/ddnsmngr/ddns_url_lib.sh

fail=0
total=0
parsed=0
scriptbased=0

check_url() {
	f="$1"; branch="$2"; u="$3"
	[ -z "$u" ] && return
	total=$((total + 1))

	if ! ddns_parse_authority "$u"; then
		case "$u" in
			http://*|https://*)
				echo "PARSE FAIL  $f/$branch: '$u'"; fail=1 ;;
			*)
				echo "info: script-based provider (no authority): $f/$branch: '$u'"
				scriptbased=$((scriptbased + 1)) ;;
		esac
		return
	fi
	parsed=$((parsed + 1))

	# round-trip with no overrides must reproduce the url
	rt=$(ddns_rebuild_url "$u" "" "" "")
	if [ "$rt" != "$u" ]; then
		echo "ROUNDTRIP   $f/$branch: '$u' -> '$rt'"; fail=1
	fi
}

for f in files/ddns-script/server/*.json files/inadyn/server/*.json; do
	[ -f "$f" ] || continue
	for branch in ipv4 ipv6; do
		u=$(jq -r ".${branch}.url // empty" "$f" 2>/dev/null)
		check_url "$f" "$branch" "$u"
	done
done

# --- override spot-checks (no preset dependency) ---
spot() {
	got=$(ddns_rebuild_url "$1" "$2" "$3" "$4")
	if [ "$got" != "$5" ]; then
		echo "OVERRIDE    in='$1' https='$2' host='$3' port='$4' => '$got' (want '$5')"; fail=1
	fi
}
# force https on an http url (userinfo + path preserved)
spot "http://[USERNAME]:[PASSWORD]@members.dyndns.org/v3/update?h=[DOMAIN]" "1" "" "" \
     "https://[USERNAME]:[PASSWORD]@members.dyndns.org/v3/update?h=[DOMAIN]"
# swap host only
spot "http://ip4.ddnss.de/upd.php?ip=[IP]" "" "myhost.example" "" \
     "http://myhost.example/upd.php?ip=[IP]"
# custom non-default port
spot "http://ip4.ddnss.de/upd.php?ip=[IP]" "" "" "8080" \
     "http://ip4.ddnss.de:8080/upd.php?ip=[IP]"
# default port is omitted (http+80)
spot "http://ip4.ddnss.de/upd.php" "" "" "80" \
     "http://ip4.ddnss.de/upd.php"
# script-based provider is passed through untouched
spot "update_freedns.sh" "1" "x" "443" "update_freedns.sh"

echo "----"
echo "urls: $total   parsed: $parsed   script-based: $scriptbased   $([ $fail -eq 0 ] && echo PASS || echo FAIL)"
exit $fail
