#!/usr/bin/env bash
# bw — Bitwarden CLI wrapper (Docker containerized, host stays clean).
#
# Usage:
#   bw login           (interactive — prompts for email/master password/2FA)
#   bw unlock          (interactive — prints export BW_SESSION=... line)
#   bw unlock --raw    (prints only the session key, for scripting)
#   bw list items
#   bw get item <name-or-id>
#   bw sync
#   bw status
#
# Session management:
#   After `bw unlock`, capture the session key:
#     export BW_SESSION=$(bw unlock --raw)
#   The wrapper passes BW_SESSION through automatically if already set.
#
# Data persistence:
#   BW data.json lives at ~/.local/share/bw-cli/ mounted into the container,
#   so login state persists across invocations.
set -euo pipefail

IMAGE="${BW_CLI_IMAGE:-reachableceo-bw-cli:2026.7.0}"
DATA_DIR="${HOME}/.local/share/bw-cli"

mkdir -p "$DATA_DIR"

# Detect TTY for interactive commands (login, unlock)
INTERACTIVE=""
if [ -t 0 ] && [ -t 1 ]; then
    INTERACTIVE="-it"
fi

# Pass BW_SESSION through if set
SESSION_ARGS=()
if [ -n "${BW_SESSION:-}" ]; then
    SESSION_ARGS+=( -e "BW_SESSION=${BW_SESSION}" )
fi

CONTAINER_NAME="reachableceo-bw-cli-$(date +%s)"

exec docker run --rm $INTERACTIVE \
    --user "$(id -u):$(id -g)" \
    --name "$CONTAINER_NAME" \
    -e HOME=/home/bw \
    -v "${DATA_DIR}:/home/bw/.config" \
    "${SESSION_ARGS[@]}" \
    "$IMAGE" "$@"
