#!/bin/sh
#
# $NetBSD: unbound,v 1.2 2017/10/25 09:13:41 roy 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()
{
	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"
