#!/bin/bash

# Bring up a NetworkManager GlobalProtect VPN with openconnect on the
# command line with nmcli.

# Dave Love, 2020-05-01, after David Woodhouse
# <http://lists.infradead.org/pipermail/openconnect-devel/2020-April/005691.html>.
# FreeBSD licence to the extent it's not derived from DW's post.

usage="Usage: $1 <VPN config name> [<username>]
<username> defaults to \$LOGNAME."
if [[ $# -lt 1 || $# -gt 2 ]]; then
    echo 1>&2 "$usage"
    exit 1
fi
if [[ $1 = --help ]]; then
    echo "$usage"
    exit 0
fi
VPN=$1
[[ $# = 2 ]] && LOGNAME=$2
if ! nmcli c show | grep -q "$VPN"; then
    echo 1>&2 "VPN \"not configured for NetworkManager\""
    exit 1
fi
vpndata=$(nmcli c show "$VPN" | grep '^vpn\.data')
gateway=$(echo "$vpndata" | sed -E -e 's/^.*gateway = ([^,]+).*$/\1/')
[[ -z $2 ]] && LOGNAME=$2
COOKIE=
eval $(/usr/sbin/openconnect --user "$LOGNAME" --authenticate -q --usergroup=gateway --protocol=gp $gateway)
if [[ -z $COOKIE || -z $FINGERPRINT || -z $HOST ]]; then
    echo 1>2 "Autentication as $LOGNAME failed"
    exit 1
fi
nmcli --ask con up "$VPN" passwd-file <(echo "\
vpn.secrets.cookie:$COOKIE
vpn.secrets.gwcert:$FINGERPRINT
vpn.secrets.gateway:$HOST")
