#!/bin/sh

ovpn_directory="/etc/openvpn/client/ovpn-enabled"
current_ovpn_path="/etc/openvpn/client/current.ovpn"

if [ "$(id -u)" -ne 0 ]; then
    echo "This script needs root privileges to interact with the openvpn service."
    exit 1
fi

prior_ovpn_path="$(readlink "${current_ovpn_path}")"
new_ovpn_path="${prior_ovpn_path}"

# TODO: Add the ability to pass arbitrary ovpn files.
# Choose a random VPN configuration inside /etc/openvpn/ovpn-enabled until a new one is selected.
while [ "${new_ovpn_path}" = "${prior_ovpn_path}" ]; do
    new_ovpn_path="$(shuf -n1 -e "${ovpn_directory}"/*)"
done

echo "OpenVPN is currently connected to $(basename "${prior_ovpn_path}" .ovpn)"
echo "Switching to OpenVPN configuration $(basename "${new_ovpn_path}" .ovpn)"

ln -fs "${new_ovpn_path}" "${current_ovpn_path}"

echo "Restarting OpenVPN service."
systemctl restart openvpn

# TODO: Add a way to report any errors. Look at systemctl is-active and is-failed.
