#!/system/bin/sh

dns1="$(getprop net.dns1)"
dns2="$(getprop net.dns2)"
eth0_dns1="$(getprop dhcp.eth0.dns1)"
eth0_dns2="$(getprop dhcp.eth0.dns2)"

RESOLV_CONF="/etc/resolv.conf"
TMP_FILE="/storage/resolv.conf.$$"
DEFAULT_DNS="nameserver 8.8.8.8\nnameserver 8.8.4.4"

dnses=""
for dns in "$dns1" "$dns2" "$eth0_dns1" "$eth0_dns2"
do
        if [ -z "$dns" ] ; then
                continue
        fi
        if [[ "$CONTENT" == *"$dns"* ]] ; then
                continue
        fi
        if [ "$dns" = "0.0.0.0" ] ; then
                continue
        fi
        # test that we got an IPv4 address
        if [ "$(echo "$dns" | tr -dc '.' | wc -c)" -ne 3 ] ; then
                continue
        fi
        dnses="${dnses}${dns}"
done

if [ -z "${dnses}" ] ; then
        dns1="8.8.8.8"
        dns2="8.8.4.4"
fi

CONTENT=""
for dns in "$dns1" "$dns2" "$eth0_dns1" "$eth0_dns2"
do
        if [ -z "$dns" ] ; then
                continue
        fi
        if [[ "$CONTENT" == *"$dns"* ]] ; then
                continue
        fi
        if [ "$dns" = "0.0.0.0" ] ; then
                continue
        fi
        CONTENT="${CONTENT}nameserver $dns\n"
done

if [ "$CONTENT" = "nameserver" ] ; then
        CONTENT="$DEFAULT_DNS"
fi

echo -e "$CONTENT" > "$TMP_FILE"

if [ "$CONTENT" != "$(cat $RESOLV_CONF 2> /dev/null)" ] ; then
        cp "$TMP_FILE" "$RESOLV_CONF"
fi
rm -f "$TMP_FILE"

exit 0
