#!/usr/bin/with-contenv bash

# Needed for the variables defined
source /etc/scripts/openvpn-config-validation.sh

echo "[OpenVPN] using provider: ${OPENVPN_PROVIDER}" | ts '%Y-%m-%d %H:%M:%S'

echo "[OpenVPN] Start Script: /usr/sbin/openvpn --reneg-sec 0 --disable-occ --auth-nocache --mute-replay-warnings --pull-filter ignore 'ping' --pull-filter ignore 'ping-restart' --pull-filter ignore 'route-ipv6' --pull-filter ignore 'ifconfig-ipv6 --pull-filter ignore 'tun-ipv6' --pull-filter ignore 'dhcp-option DNS6' --pull-filter ignore 'reneg-sec' --pull-filter ignore 'persist-tun' --pull-filter ignore 'block-outside-dns' ${OPENVPN_OPTIONS} --config ${VPN_CONFIG}" | ts '%Y-%m-%d %H:%M:%S'

if [[ "${DEBUG}" == "true" ]]; then
    echo "[OpenVPN] Contents of ovpn file ${VPN_CONFIG} as follows..." | ts '%Y-%m-%d %H:%M:%S'; cat "${VPN_CONFIG}"

    echo "[OpenVPN] Adding ${NAME_SERVER_ITEM} to /etc/resolv.conf" | ts '%Y-%m-%d %H:%M:%S'

    if [[ "${VPN_PROVIDER}" == "pia" ]]; then
        echo "[OpenVPN] PIA config files available as follows..." | ts '%Y-%m-%d %H:%M:%S'; cat "${VPN_PROVIDER_CONFIGS}/list.txt" | grep ".ovpn" | tr '\n' '|' | sed 's/\b.ovpn\b//g'
    fi

    if [[ "${VPN_PROVIDER}" == "surfshark" ]]; then
        echo "[OpenVPN] Surfshark config files available as follows..." | ts '%Y-%m-%d %H:%M:%S'; cat "${VPN_PROVIDER_CONFIGS}/list.txt" | grep "_${OPENVPN_PROTOCOL,,}.ovpn" | tr '\n' '|' | sed 's/\b.ovpn\b//g'
    fi
fi

/usr/sbin/openvpn \
    --reneg-sec 0 \
    --disable-occ \
    --auth-nocache \
    --mute-replay-warnings \
    --pull-filter ignore 'route-ipv6' \
    --pull-filter ignore 'ifconfig-ipv6' \
    --pull-filter ignore 'tun-ipv6' \
    --pull-filter ignore 'dhcp-option DNS6' \
    --pull-filter ignore 'reneg-sec' \
    --pull-filter ignore 'persist-tun' \
    --pull-filter ignore 'block-outside-dns' \
    ${OPENVPN_OPTIONS} --config "${VPN_CONFIG}"

echo "[tvheadend] Public IP: $(curl -s ifconfig.me)" | ts '%Y-%m-%d %H:%M:%S'
