#!/usr/bin/env bash
set -euo pipefail

RUNTIME_ENV_FILE="${WELLAU_SSLVPN_RUNTIME_ENV_FILE:-$HOME/.config/wellau-sslvpn/runtime.env}"
if [[ -f "$RUNTIME_ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$RUNTIME_ENV_FILE"
fi

REPO_DIR="${SSLVPN_REPO_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
ENV_FILE="${WELLAU_SSLVPN_ENV_FILE:-$REPO_DIR/.env}"
if [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
fi

PID_FILE="/tmp/wellau-vpn.pid"
VPN_URL="${WELLAU_VPN_GATEWAY:-vpn.wellau.com}"
VPN_USERNAME="${WELLAU_VPN_USERNAME:-wellau-ops-admin}"

if [[ -f "$PID_FILE" ]]; then
  old_pid="$(cat "$PID_FILE" 2>/dev/null || true)"
  if [[ -n "$old_pid" ]] && ps -p "$old_pid" >/dev/null 2>&1; then
    echo "Stopping existing VPN process $old_pid"
    sudo kill "$old_pid" || true
    sleep 2
  fi
fi

args=("$VPN_URL")
if [[ -n "$VPN_USERNAME" ]]; then
  args=(--user "$VPN_USERNAME" "${args[@]}")
fi

echo "Starting interactive OpenConnect session for $VPN_URL"
echo "Username source: $ENV_FILE"
echo "Authentication order: verification code first, then account password."
echo "Keep this terminal open while connected."
sudo openconnect "${args[@]}"
