# 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"
        fi
    done
fi

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

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

# Apply the dns info that was received from dhcp or from lts.conf
if [ -n "$DNS_SERVER" ] || [ -n "$SEARCH_DOMAIN" ]; then
    # 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_method=resolvconf
        resolv=/etc/resolvconf/resolv.conf.d/base
    else
        resolv_method=static
        resolv=/etc/resolv.conf
    fi

    # Check if $resolv is writable
    if echo '# Generated by ltsp' 2>/dev/null > "$resolv"; then
        if [ -n "$SEARCH_DOMAIN" ]; then
            echo "search $SEARCH_DOMAIN" >> "$resolv"
        fi
        for n in $DNS_SERVER; do
            echo "nameserver $n" >> "$resolv"
        done
    fi
fi
true
