#!/usr/bin/env bash

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

# TODO: Investigate better ways to check for rootness. This is just a courtesy message, though.
#   Non-root users will not be able to do anything with this anyway.
if [ "$(whoami)" != "root" ]; then
    echo "This script needs root privileges to interact with the openvpn service."
    exit
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.
