#!/bin/bash
#
# Univention Server
#  network script: modify resolv.conf
#
# SPDX-FileCopyrightText: 2021-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

# Bug #37689: this script is "sourced", not forked; Do not "exit" the process!
test -n "${interface:-}" || return 0
[ "$(ucr get "interfaces/${interface}/type")" = dhcp ] || return 0
[ -x /usr/share/univention-server/univention-fix-ucr-dns ] || return 0

make_resolv_conf () {
	local ns
	eval "$(ucr shell '^nameserver[123]$')"

	# shellcheck source=/dev/null
	if ( . /usr/share/univention-lib/ucr.sh ; is_ucr_true "nameserver/external" ); then
		return 0  # do not touch /etc/resolv.conf at all
	fi

	[ "${old_domain_name_servers:-}" != "${new_domain_name_servers:-}" ] ||
		[ "${old_dhcp6_name_servers:-}" != "${new_dhcp6_name_servers:-}" ] ||
		return 0

	# IPv4
	# shellcheck disable=SC2086
	set -- ${new_domain_name_servers:-}  # IFS
	# IPv6
	for ns in ${new_dhcp6_name_servers:-}  # IFS
	do
		set -- ${1:+"$@"} "$(link_local "$ns")"
	done

	for ns in "$@"
	do
		shift
		set -- "$@" --dnsserver "$ns"
	done

	if [ -z "$*" ] ; then
		# no nameservers have been specified - do not touch existing config
		return 0
	fi

	# On a joined UCS system with local DNS server, the DHCP nameserver are automatically
	# converted to nameserver[123] resp. dns/forwarder[123] and the local system is also
	# added to nameserver[123] if not already present (Bug #44462).
	# shellcheck source=/dev/null
	if	[ -e /var/univention-join/joined ] &&
		( . /usr/share/univention-lib/base.sh ; is_domain_controller )
	then
		if [ -n "$new_ip_address" ]; then
			/usr/share/univention-server/univention-fix-ucr-dns --no-ucr --force-self --own-ip "$new_ip_address" "$@"
		else
			/usr/share/univention-server/univention-fix-ucr-dns --no-ucr --force-self "$@"
		fi
	else
		# on unjoined systems or non-domaincontrollers do not add own IP address
		/usr/share/univention-server/univention-fix-ucr-dns --no-ucr --no-self "$@"
	fi
}
ns_in_list () {
	case "$2" in
	"$1 "*|*" $1 "*|*" $1") return 0 ;;
	*) return 1 ;;
	esac
}
link_local () {  # append "%interface" to link-local-address
	case "$1" in
	[fF][eE]80:*) echo "${1}%${interface}" ;;
	*) echo "$1" ;;
	esac
}
