#!/bin/bash # shellcheck disable=SC2034 die() { [ -n "$oc_pid" ] && kill -s TERM "$oc_pid" echo "exitting..." rm -f $PIPE exit 0 } trap 'die' SIGTERM SIGQUIT SIGINT PIPE="/var/run/vpnd.sock" oc_pid= up_name= [ -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" "status") is_really_up() { [ -n "$oc_pid" ] && if ! kill -0 "$oc_pid"; then oc_pid= up_name= fi } in_arr() { declare -n arr="$2" for value in "${arr[@]}"; do [ "$value" = "$1" ] && return 0 done return 1 } down() { is_really_up [ -z "$oc_pid" ] && return kill -s TERM "$oc_pid" wait "$oc_pid" oc_pid= up_name= } up() { is_really_up [ -n "$oc_pid" ] && down openconnect --config "/etc/openconnect/config_$1" & oc_pid="$!" up_name="$1" } status() { is_really_up echo "$up_name" > $PIPE } main() { mkfifo $PIPE -m666 while :; do read -r cmd ifname < $PIPE if ! in_arr "$cmd" "COMMANDS"; then echo "ERROR: Invalid command $cmd" > $PIPE else case "$cmd" in "up") if ! in_arr "$ifname" "CONFIGS"; then echo "ERROR: Invalid interface $ifname" > $PIPE else up "$ifname" echo "$ifname" > $PIPE fi ;; "down") down; echo "down" > $PIPE;; "status") status;; esac fi done } echo "Running..." main