#!/usr/bin/env bash

VPN_SRC="${HOME}/.wireguard"
INDENT="  ";

function usage()
{
    echo "usage: vpn [list, status, {up|down} <name>]";
    echo "${INDENT}list          List all VPNs";
    echo "${INDENT}status        Shows the vpn status (equivalent to calling the script without any arguments)";
    echo "${INDENT}up <name>     Bring up the VPN named <name>";
    echo "${INDENT}down <name>   Take down the VPN named <name>";
}

function show_status()
{
    echo "VPN Status";
    echo "==========";
    ${WG};

    echo "";
    echo "${INDENT}Routes";
    echo "${INDENT}------";
    ip route | cut --delim " " --fields 1,3 | column -t -s' ' | sed "s/^/${INDENT}/g";
    echo "";
}

function list_vpns()
{
    echo "Available VPNs (from ${VPN_SRC}):";
    echo "==============================================";
    pushd "${VPN_SRC}" > /dev/null;
    ls -1 *.conf | sed "s/.conf$//g" | sort | sed "s/^/${INDENT}- /g";
    popd > /dev/null;
}

function do_vpn_action()
{
    CMD="${1}";
    TARGET="${2}";
    ${WGQUICK} "${CMD}" "${VPN_SRC}/${TARGET}.conf";
}

#make sure we have our environment straight
WGQUICK="$(which wg-quick)";
if [ "${WGQUICK}" == "" ]
then
    echo "ERROR: wg-quick (and thus Wireguard) is not installed.";
    WGQUICK="echo FAKE: \"wg-quick\"";
else
    WGQUICK="sudo ${WGQUICK}";
fi;

WG="$(which wg)";
if [ "${WG}" == "" ]
then
    echo "ERROR: wg (and thus Wireguard) is not installed.";
    WG="echo FAKE: \"wg\"";
else
    WG="sudo ${WG}";
fi;

case "${1}" in
    "list")
        list_vpns;
        ;;
    "" | "status")
        show_status;
        ;;
    "up" | "down")
        if [ "${2}" == "" ]
        then
            usage;
        else
            do_vpn_action "${1}" "${2}";
        fi;
        ;;
    *)
        usage;
        ;;
esac;

