# set to defaults from DHCP if not specified in lts.conf
if [ -z "$DNS_SERVER" ]; then
    for dns in $IPV4DNS0 $IPV4DNS1 ; do
        # ignore nameserver of 0.0.0.0, which ipconfig may return if both
        # nameservers aren't specified.
        if [ "$dns" != "0.0.0.0" ]; then
            DNS_SERVER="${DNS_SERVER+$DNS_SERVER }$dns"
        fi
    done
fi

# If no DNS_SERVER was defined in lts.conf or in DHCP (e.g. IPAPPEND=3),
# check if the LTSP server or the gateway are DNS servers.
if [ -z "$DNS_SERVER" ] && [ -x /usr/bin/dig ]; then
    gateway=$(LANG=C ip route | sed -n 's/default via \([0-9.]*\).*/\1/p')
    test "$gateway" != "$SERVER" || unset gateway
    for dns in $SERVER $gateway; do
        if dig +time=1 +tries=1 +short "@$dns" localhost >/dev/null 2>&1; then
            DNS_SERVER="$dns"
            break
        fi
    done
fi

# If klibc ipconfig is available, do a "fake" DHCP request to get the DNS
if [ -z "$DNS_SERVER" ] && [ -x /usr/lib/klibc/bin/ipconfig ]; then
    # Remember non empty settings and append them after the new ones
    existing_contents=$(grep -sv "=''$" /run/net-$DEVICE.conf)
    if /usr/lib/klibc/bin/ipconfig -t 3 -n "$DEVICE" >/dev/null &&
        [ -f "/run/net-$DEVICE.conf" ]
    then
        if [ -n "$existing_contents" ]; then
            echo "$existing_contents" >> "/run/net-$DEVICE.conf"
        fi
        # Don't blindly source it now, we might have changed some vars
        for dns in $(. "/run/net-$DEVICE.conf" && echo $IPV4DNS0 $IPV4DNS1); do
            if [ "$dns" != "0.0.0.0" ]; then
                DNS_SERVER="${DNS_SERVER+$DNS_SERVER }$dns"
            fi
        done
    fi
fi

if [ -z "$SEARCH_DOMAIN" ] && [ -n "$DNSDOMAIN" ]; then
    SEARCH_DOMAIN="$DNSDOMAIN"
fi

# Exit if we don't have anything to apply
test -n "$DNS_SERVER$SEARCH_DOMAIN" || return 0

# Deal with systemd-resolved.
# The symlink may be relative or absolute, so better use grep.
if ls -l /etc/resolv.conf | grep -q /run/systemd/resolve/; then
    # We can't do per link DNS without systemd-networkd
    # (e.g. when using network-manager), so define them globally
    mkdir -p /etc/systemd/resolved.conf.d
    {
        echo "[Resolve]"
        test -n "$DNS_SERVER" && echo "DNS=$DNS_SERVER"
        test -n "$SEARCH_DOMAIN" && echo "Domains=$SEARCH_DOMAIN"
    } > /etc/systemd/resolved.conf.d/ltsp.conf
else
    # Deal with resolvconf
    if [ -x /sbin/resolvconf ] && ( [ -L /etc/resolv.conf ] || [ -e /var/lib/resolvconf/convert ] ); then
        mkdir -p /etc/resolvconf/resolv.conf.d/
        resolv=/etc/resolvconf/resolv.conf.d/base
    else
        resolv=/etc/resolv.conf
        # Remove possibly dangling symlinks
        rm -f "$resolv"
    fi

    {
        echo "# Generated by LTSP"
        test -n "$SEARCH_DOMAIN" && echo "search $SEARCH_DOMAIN"
        for n in $DNS_SERVER; do
            echo "nameserver $n"
        done
    } > "$resolv"
fi
