#!/bin/bash
#
# Parses DHCP options from openvpn to update resolv.conf
# To use set as 'up' and 'down' script in your openvpn *.conf:
# up /etc/openvpn/update-resolv-conf
# down /etc/openvpn/update-resolv-conf
#
# Used snippets of resolvconf script by Thomas Hood and Chris Hanson.
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# Example envs set from openvpn:
#
#     foreign_option_1='dhcp-option DNS 193.43.27.132'
#     foreign_option_2='dhcp-option DNS 193.43.27.133'
#     foreign_option_3='dhcp-option DOMAIN be.bnc.ch'
#

command -v resolvconf || exit 0
[ "$script_type" ] || exit 0
[ "$dev" ] || exit 0

resolvconf_iface_prefix() {
    [[ -f /etc/resolvconf/interface-order ]] || return 0
    local iface
    while read -r iface; do
        [[ $iface =~ ^([A-Za-z0-9-]+)\*$ ]] || continue
        echo "${BASH_REMATCH[1]}." && return 0
    done < /etc/resolvconf/interface-order
}

case "$script_type" in
  up)
    NMSRVRS=""
    SRCHS=""
    for optionvarname in ${!foreign_option_*} ; do
        option="${!optionvarname}"
        echo "$option"
        # Quoted read: no word-splitting or globbing of the pushed value (an unquoted expansion
        # would let a value like `DOMAIN *` glob against the CWD into the search line).
        read -r part1 part2 part3 <<<"$option"
        if [ "$part1" = "dhcp-option" ] ; then
            if [ "$part2" = "DNS" ] ; then
                # Only trust a bare IP (v4 dotted-quad or v6 hex/colon) as a nameserver; drop a
                # pushed value carrying trailing junk rather than writing it into resolv.conf.
                if [[ "$part3" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || [[ "$part3" =~ ^[0-9A-Fa-f:]+$ ]] ; then
                    NMSRVRS="${NMSRVRS:+$NMSRVRS }$part3"
                fi
            elif [ "$part2" = "DOMAIN" ] ; then
                SRCHS="${SRCHS:+$SRCHS }$part3"
            fi
        fi
    done
    R=""
    servers=()
    [ "$SRCHS" ] && R="search $SRCHS
"
    for NS in $NMSRVRS ; do
            R="${R}nameserver $NS
"
        servers+=(${NS})
    done

    [[ "$(readlink -f "$(command -v resolvconf)")" != *resolvectl ]] && resolvconf -u
    if [[ -z "${is_wireguard}" ]]; then
        echo -n "$R" | resolvconf -a "${dev}.openvpn"
    else
        echo -n "$R" | resolvconf -a "$(resolvconf_iface_prefix)${dev}" -m 0 -x
    fi

    ;;
  down)
    if [[ -z "${is_wireguard}" ]]; then
        resolvconf -d "${dev}.openvpn"
    else
        resolvconf -d "$(resolvconf_iface_prefix)${dev}" -f
    fi

    ;;
esac


