#!/bin/bash
# shellcheck disable=SC2034

die() {
    echo "exitting..."
    rm -f $PIPE
    exit 0
}

trap 'die' SIGTERM SIGQUIT SIGINT

PIPE="/var/run/vpnd.sock"
oc_pid=

[ -p $PIPE ] && exit 1
[ "$(id -u)" != "0" ] && exit 1

declare -a CONFIGS
for config in /etc/openconnect/config_*; do
    config="$(basename "$config")"
    CONFIGS+=("${config#config_}")
done

COMMANDS=("up" "down")

in_arr() {
    declare -n arr="$2"

    for value in "${arr[@]}"; do
        [ "$value" = "$1" ] && return 0
    done
    return 1
}

down() {
    [ -z "$oc_pid" ] && return
    kill -s TERM $oc_pid
    wait $oc_pid
    oc_pid=
}

up() {
    [ -n "$oc_pid" ] && down
    openconnect --config "/etc/openconnect/config_$1" &
    oc_pid="$!"
}

main() {
    mkfifo $PIPE -m666

    while :; do
        read -r cmd ifname < $PIPE

        if ! in_arr "$ifname" "CONFIGS"; then
            echo "ERROR: Invalid interface $ifname" > $PIPE
        elif ! in_arr "$cmd" "COMMANDS"; then
            echo "ERROR: Invalid command $cmd" > $PIPE
        else
            case "$cmd" in
                "up") up "$ifname" > $PIPE ;;
                "down") down > $PIPE ;;
            esac
        fi
    done
}

main
