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

usage() {
  cat >&2 <<'EOF'
Usage:
  bw_run.sh <bw-args...>
  bw_run.sh --keep-unlocked <seconds> <bw-args...>

Reads Bitwarden master password from GNOME Keyring (Secret Service) at:
  app=openclaw, name=bw_master_password

Then:
  - bw unlock (captures BW_SESSION)
  - runs: bw <args>
  - locks the vault on exit (always)

--keep-unlocked: delay locking for N seconds after the command finishes.
EOF
}

die() { echo "bw_run: $*" >&2; exit 1; }

KEEP_SECS=0
if [[ "${1-}" == "-h" || "${1-}" == "--help" ]]; then
  usage
  exit 0
fi
if [[ "${1-}" == "--keep-unlocked" ]]; then
  [[ $# -ge 3 ]] || { usage; exit 2; }
  KEEP_SECS="$2"
  shift 2
  [[ "$KEEP_SECS" =~ ^[0-9]+$ ]] || die "--keep-unlocked requires integer seconds"
fi

command -v secret-tool >/dev/null 2>&1 || die "missing dependency: secret-tool"
command -v bw >/dev/null 2>&1 || die "missing dependency: bw (Bitwarden CLI)"

# Run bw command (require args) — do this early so accidental runs don't touch keyring
[[ $# -ge 1 ]] || { usage; exit 2; }

cleanup() {
  # optional grace period (only if requested)
  if [[ "${KEEP_SECS}" -gt 0 ]]; then
    sleep "${KEEP_SECS}" || true
  fi
  # best-effort lock + scrub env
  bw lock >/dev/null 2>&1 || true
  unset BW_SESSION MASTER KEEP_SECS
}
trap cleanup EXIT

# Read master password from keyring (no output).
# Fallback: if keyring access fails (common in non-GUI / no DBus), prompt on TTY.
MASTER=""
if MASTER="$(secret-tool lookup app openclaw name bw_master_password 2>/dev/null)"; then
  :
else
  if [[ -t 0 ]]; then
    echo "bw_run: keyring lookup failed (no secret or no Secret Service/DBus). Falling back to TTY prompt." >&2
    read -r -s -p "Bitwarden master password: " MASTER
    echo >&2
  else
    die "cannot read master password from keyring (app=openclaw name=bw_master_password). If running under SSH/cron, DBus/gnome-keyring may be unavailable. Re-store it or run from a desktop session."
  fi
fi
[[ -n "${MASTER}" ]] || die "empty master password (keyring returned empty or prompt cancelled)"

# Unlock and capture session token (raw)
export BW_SESSION
if ! BW_SESSION="$(bw unlock --raw "${MASTER}" 2>/dev/null)"; then
  # If keyring returned something but it's wrong/stale, allow interactive retry.
  if [[ -t 0 ]]; then
    echo "bw_run: bw unlock failed using keyring secret. You may have stored the wrong value. Retry with TTY prompt." >&2
    read -r -s -p "Bitwarden master password: " MASTER
    echo >&2
    BW_SESSION="$(bw unlock --raw "${MASTER}" 2>/dev/null)" || die "bw unlock failed again. Re-store the correct master password and/or check bw status."
  else
    die "bw unlock failed. Check master password, serverUrl, and that you're logged in (bw status)."
  fi
fi
[[ -n "${BW_SESSION}" ]] || die "bw unlock returned empty session token (unexpected)"

bw "$@"
