#!/bin/sh -e
#
# This update hook is **disabled** by default: the execute bit is not set.
#
# This hook can be problematic, especially if the
# upstream nameservers do not perform DNSSEC validation, or if a
# "forward-zone" declaration for the root zone has been statically
# configured by the administrator. In previous versions, the hook was
# enabled by default, but it is now disabled by default. It can be
# explicitly enabled by running "chmod +x /etc/resolvconf/update.d/unbound".
#
# If enabled (by setting the execute bit), upstream nameservers
# supplied by resolvconf will be configured into the running Unbound instance
# via the "unbound-control forward" command.
#

PATH=/usr/sbin:/usr/bin:/sbin:/bin

if [ ! -x /usr/sbin/unbound ]; then
    exit 0
fi

if [ ! -f /etc/unbound/unbound_control.key ]; then
    exit 0
fi

if [ ! -x /lib/resolvconf/list-records ]; then
    exit 1
fi

RESOLVCONF_FILES="$(/lib/resolvconf/list-records)"

if [ -n "$RESOLVCONF_FILES" ]; then
    NS_IPS="$(sed -rne 's/^[[:space:]]*nameserver[[:space:]]+//p' $RESOLVCONF_FILES \
        | egrep -v '^(127\.|::1)' | sort -u)"
else
    NS_IPS=""
fi

if [ -n "$NS_IPS" ]; then
    FWD="$(echo $NS_IPS | tr '\n' ' ')"
    unbound-control forward $FWD 1>/dev/null 2>&1 || true
else
    unbound-control forward off 1>/dev/null 2>&1 || true
fi
