#!/bin/sh
#
# $NetBSD: unbound,v 1.2.18.1 2026/07/03 17:58:23 martin Exp $
#

# PROVIDE: named
# REQUIRE: NETWORKING mountcritremote syslogd
# BEFORE:  DAEMON
# KEYWORD: chrootdir

$_rc_subr_loaded . /etc/rc.subr

name="unbound"
rcvar=$name
command="/usr/sbin/${name}"
pidfile="/var/run/${name}.pid"
required_files="/etc/${name}/${name}.conf"
start_precmd="unbound_precmd"
extra_commands="reload"

unbound_migrate()
{
	local src="$1"
	local dst="$2$1"
	echo "Migrating $src to $dst"
(
	diff=false
	cd "$src"
	mkdir -p "$dst"
	for f in $(find . -type f)
	do
		f="${f##./}"
		case "$f" in
		*/*)
			ds="$(dirname "$f")"
			dd="$dst/$ds"
			mkdir -p "$dd"
			chmod "$(stat -f "%p" "$ds" |
			    sed -e 's/.*\([0-7][0-7][0-7][0-7]\)$/\1/g')" "$dd"
			chown "$(stat -f %u:%g "$ds")" "$dd"
			;;
		*)
			;;
		esac
		if [ -r "$dst/$f" ]
		then
			if ! cmp "$f" "$dst/$f"; then
				diff=true
			fi
		else
			cp -p "$f" "$dst/$f"
		fi
	done
	if $diff; then
		echo "Cannot complete migration because files are different"
		echo "Run 'diff -r $src $dst' resolve the differences"
	else
		rm -fr "$src"
		ln -s "$dst" "$src"
	fi
)
}

unbound_precmd()
{
	local root_key

	if checkyesno unbound_auto_trust_anchor; then
		root_key=$(su -m _unbound -c \
		    'unbound-checkconf -o auto-trust-anchor-file') || return $?
		if [ -n "$root_key" ] && [ ! -f /etc/unbound/"$root_key" ]
		then
			echo Bootstrapping Unbound DNS trust anchors.
			su -m _unbound -c 'unbound-anchor -a "$1"' -- \
			    /etc/unbound/"$root_key"
		fi
	fi

	if [ -z "$unbound_chrootdir" ]; then
		return
	fi

	if [ ! -h /etc/unbound ]; then
		unbound_migrate /etc/unbound ${unbound_chrootdir}
	fi
}

load_rc_config $name
run_rc_command "$1"
