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

BW_ITEM_ID="00103432-dabe-4fad-b0c0-0f40ab1ebb36"
export NODE_EXTRA_CA_CERTS="$HOME/.config/bitwarden-certs/vaultwarden-agres-site.pem"

# Ensure Bitwarden is available.
if ! command -v bw >/dev/null 2>&1; then
  echo "Error: bw CLI not found." >&2
  exit 1
fi

# Ensure we have a usable Bitwarden session.
BW_STATUS="$(bw status 2>/dev/null | jq -r '.status')"

case "$BW_STATUS" in
  unauthenticated)
    echo "Bitwarden is not logged in. Logging in..."
    bw login
    export BW_SESSION="$(bw unlock --raw)"
    ;;
  locked)
    echo "Bitwarden vault is locked. Unlocking..."
    export BW_SESSION="$(bw unlock --raw)"
    ;;
  unlocked)
    # Already unlocked in this shell/session.
    ;;
  *)
    echo "Error: unknown Bitwarden status: $BW_STATUS" >&2
    exit 1
    ;;
esac

# Pull latest vault data if reachable. Do not fail hard if sync is unavailable.
bw sync >/dev/null 2>&1 || echo "Warning: bw sync failed; using local Bitwarden cache." >&2

VPN_USER="$(bw get username "$BW_ITEM_ID")"
VPN_PASS="$(bw get password "$BW_ITEM_ID")"

if [[ -z "$VPN_USER" || -z "$VPN_PASS" ]]; then
  echo "Error: username or password is empty for Bitwarden item: $BW_ITEM_ID" >&2
  exit 1
fi

# Feed only the VPN password through stdin.
# OpenConnect will still prompt interactively for 2FA if the server requires it.
{
  printf '%s\n' "$VPN_PASS"
  cat /dev/tty
} | sudo openconnect --timestamp --dump-http-traffic \
  --protocol=anyconnect \
  --user="$VPN_USER" \
  --passwd-on-stdin \
  --useragent='AnyConnect' \
  --gnutls-priority="NORMAL:-VERS-ALL:+VERS-TLS1.2:+RSA:+AES-128-CBC:+SHA1" \
  vpn-ac.uni-heidelberg.de/2fa
