#!/bin/bash
# By Michael Blaschek
# Date 31.07.2023
# CC BY 4.0 International
# University of Vienna, Austria
# Department of Meteorology and Geophysics
# img.univie.ac.at

# Description:
# Connect to VPN from the University of Vienna
# You need to download the F5 VPN Client from the ZID website (zid.univie.ac.at/vpn)
# The executable works only for VPN@UNIVIE. Follow the instructions on the ZID website
# on how to install the package depending on your Linux distro.
# Maybe this download link works directly:
# https://vpn.univie.ac.at/public/share/BIGIPLinuxClient.tgz
#
# Steps:
# 1. run connect2vpn script
# 1.1. Checks if it can find f5fpc exe 
# 1.2. Asks for credentials
# 1.3. Asks for TOTP Code
# 1.4. Watch connection

vpninfos() {
	infos=$(f5fpc --info)
	status=$(echo "${infos}" | grep '/Common/Remote-Access' | head -n1 | cut -d' ' -f3)
	cat <<EOF
[VPN] ${status}
[VPN] Connection Information. Use Ctrl+c to end.
===============================================================================
${infos}
EOF
}

if [ $# -eq 0 ]; then
	if [ "${VPN_USER}" != "" ]; then
		echo "[VPN] using '$VPN_USER'"
	else
		read -p "[VPN] u:account username: " VPN_USER
	fi
else
	VPN_USER=$1
	echo "[VPN] Using ${VPN_USER} as username"
fi

f5fpc -v 2> /dev/null 1>/dev/null
if [ $? -ne 0 ]; then
	echo "[VPN] Install Big-IP Edge Client. f5fpc missing"
	exit 1
else
	echo "[VPN] $(f5fpc -v | head -n1)"
fi

echo
echo "[VPN] Notice: This script will continue to run in foreground!"
echo
read -p "[VPN] Full (1) or split (None) tunnel? (1/None): " REPLY
if [ "$REPLY" == "" ]; then
	echo "[VPN] Connecting split-tunnel ..."
	cmd="f5fpc -s -t vpn.univie.ac.at"
else
	echo "[VPN] Connecting full-tunnel ..."
	cmd="f5fpc -s -t vpn.univie.ac.at:8443"
fi
echo "[VPN] Testing VPN Client..."
# Show status
export -f vpninfos
init=true
while true;
do
	f5fpc --info | grep "established" > /dev/null
	if [ $? -ne 0 ]; then
		if ! $init; then
			echo "[VPN] Restarting ..."
			f5fpc -o
		fi
		echo "[VPN] Starting connection ..."
		if [ -z "$VPN_PWD" ]; then
			read -sp "[VPN] u:account password:" VPN_PWD
			echo
		fi
		read -p "[VPN] TOTP Code (6 digits/empty):" VPN_TOTP
		if [ -n "$VPN_TOTP" ]; then
			eval "${cmd} -p ${VPN_PWD} -u ${VPN_USER}@${VPN_TOTP}"
		else
			eval "$cmd -p ${VPN_PWD} -u ${VPN_USER}"
		fi
		if $init; then
			init=false
		fi
	fi
	watch -n 2 vpninfos
	read -p "[VPN] Reconnect (1) or shutdown (None): " REPLY
	if [ "$REPLY" == "" ]; then
		break
	fi
done
unset VPN_PWD VPN_USER VPN_TOTP
echo "[VPN] Shutting down ..."
# Disconnect
f5fpc -o
echo "[VPN] disconnected"
