#!/bin/sh
# bw-entrypoint.sh — Bitwarden auth lifecycle, runs inside the container.
#
# Mounted at /opt/bw/entrypoint.sh by the host-side wrapper (bw-cli.sh).
# Handles: server config, API-key login, vault unlock, sync.
# Then execs the real bw command with BW_SESSION set.
#
# API key authentication does NOT require TOTP. The API key itself is
# obtained from an authenticated web vault session, so 2FA is already
# satisfied at key-generation time.
#
# This script intentionally uses /bin/sh (not bash) for minimal container
# compatibility. shellcheck directive below silences the "not bash" note.
# shellcheck shell=sh

set -e

BW_SERVER="${BW_SERVER:-https://pwvault.turnsys.com}"

# Suppress BW CLI data-dir creation noise and telemetry.
export BW_NO_SENTRY=true

# --- Step 1: Configure server (fails harmlessly if already logged in) ---
bw config server "$BW_SERVER" >/dev/null 2>&1 || true

# --- Step 2: Login via API key (silently skips if already authenticated) ---
bw login --apikey >/dev/null 2>&1 || true

# --- Step 3: Unlock the vault ---
printf '%s' "$BW_PASSWORD" > /tmp/.bwpw
SESS=$(bw unlock --passwordfile /tmp/.bwpw --raw 2>/dev/null)
rm -f /tmp/.bwpw
if [ -z "$SESS" ]; then
    echo "bw: unlock failed. Check BW_PASSWORD in ~/.config/bw/env" >&2
    echo "    Values must be single-quoted; \$ chars get mangled if unquoted." >&2
    exit 1
fi

# --- Step 4: Sync ---
bw sync --session "$SESS" >/dev/null 2>&1 || true

# --- Step 5: Execute the requested command ---
export BW_SESSION="$SESS"
exec bw "$@"
