#!/usr/bin/sh get_service() { systemctl --type=service | grep openvpn-client@nordvpn | awk '{print $1}' } run_ping() { remote=$(grep -E '^remote [0-9.]+ [0-9]+$' $1 | cut -d ' ' -f 2) test ! -z "$remote" || exit 1 bin=$(which ping) test $? -eq 0 || echo "ping not found, please install iputils" $bin -c 4 -A $remote | tail -n 1 | cut -d / -f 5 } print_usage() { echo "usage: $(basename $0) [options] command [args]" echo "Available options:" echo " -v be verbose, show commands and variables" echo " -h print this help and exit" echo "Available commands:" echo " list [server_name_pattern]" echo " List available servers." echo " ping server_name" echo " Show round trip latency" echo " rank [server_name_pattern]" echo " Ping all servers matching pattern and rank them" echo " status" echo " Show current systemd service status, if any." echo " start|stop|restart server_name" echo " Start, stop or restart systemd service for specified server." } while getopts "vh" opt do case $opt in v) set -x shift ;; *) print_usage exit $(test $opt == "h") ;; esac done command=$1 shift case $command in list) find /etc/openvpn/client/ -type l -name "nordvpn_*${1}*.conf" \ | xargs -L1 basename \ | cut -d _ -f 2 \ | cut -d . -f 1 \ | sort -g ;; ping) file=/etc/openvpn/client/nordvpn_${1}.conf test -f "$file" || exit 1 run_ping $file ;; rank) tmp=$(mktemp) for f in $(find /etc/openvpn/client/ -type l -name "nordvpn_*${1}*.conf") do echo $(basename $f .conf | cut -d _ -f 2) $(run_ping $f) >> $tmp done sort -k 2 -n $tmp rm -f $tmp ;; status) service=$(get_service) test -z "$service" || systemctl status $service ;; start) service=$(get_service) test -z "$service" || $0 stop if [[ -x /etc/openvpn/vpnfailsafe.sh ]]; then ln -fs /etc/openvpn/vpnfailsafe.sh /etc/openvpn/client/nordvpn/updown else ln -fs /etc/openvpn/update-resolv-conf /etc/openvpn/client/nordvpn/updown fi if [[ ! -f /etc/openvpn/client/nordvpn_${1}.conf ]]; then echo "${1} is not a valid nordvpn server. Exiting." exit 1 fi systemctl $command openvpn-client@nordvpn_${1} ;; stop|restart) service=$(get_service) test -z "$service" || systemctl $command $service ;; *) print_usage exit 1 ;; esac