#! /bin/bash
set -e

# Require 1 argument (connect or disconnect)
if [ -z "$1" ]; then
    echo "Usage: guru-vpn <connect|disconnect>"
    exit 1
fi

# If we are told to disconnect
if [ "$1" == "disconnect" ]; then
    echo "Disconnecting..."
    nmcli connection down "Guru VPN"
    exit 0
fi

# If we are told to connect
if [ "$1" == "connect" ]; then
    # Attempt to disconnect, just in case we are on a stale connection
    echo "Attempting to leave stale connection if it exists"
    nmcli connection down "Guru VPN" | true

    # Generate the password
    echo "Constructing one-time password"
    vpn_pass=$(guru-sophos-password)

    # Connect
    echo "Connecting..."
    nmcli connection modify "Guru VPN" vpn.secrets "password=${vpn_pass}"
    nmcli connection up "Guru VPN"

    exit 0
fi

# If we are here, we were given an invalid command
echo "Usage: guru-vpn <connect|disconnect>"
exit 1