#!/usr/bin/env bash
# In-container interactive launcher for a RESIDENT seat (S2). Runs inside the same
# harness-seat image as a one-shot dispatch, via `podman exec -it`, into a container that
# `seat-resident-run.sh` created with --entrypoint bash and keeps parked with `sleep infinity`.
#
# Unlike seat-entrypoint.sh (one wrapper invocation, exits, container is --rm), this seeds
# credentials into the tmpfs HOME on every exec — cheap and idempotent — because a persistent
# container can outlive many attach/detach cycles and its tmpfs HOME never gets a second seed
# otherwise. Ends by exec'ing an interactive `claude`, so tmux's pane owns its pty directly.
set -uo pipefail

WORKSPACE="${1:?seat-resident-shell: workspace path required (arg 1)}"

export HOME=/seat-home
mkdir -p "$HOME" || { echo "seat-resident-shell: HOME tmpfs not writable" >&2; exit 2; }
chmod 0700 "$HOME"
# claude runs as uid 0 in here and refuses --permission-mode bypassPermissions without this.
export IS_SANDBOX=1
export TMPDIR=/tmp
export HARNESS_SEAT_CONTAINER=1

CREDENTIALS_MANIFEST="${HARNESS_SEAT_CREDENTIALS_MANIFEST:-}"
[[ -n "$CREDENTIALS_MANIFEST" && -f "$CREDENTIALS_MANIFEST" ]] \
  || { echo "seat-resident-shell: credential manifest missing from bundled runtime" >&2; exit 2; }
seed_copy() {
  local src="$1" dest="$2"
  [[ -f "$src" ]] || return 0
  mkdir -p "$(dirname "$dest")" && install -m 0600 "$src" "$dest"
}
while IFS=$'\t' read -r cred_home cred_seed; do
  [[ -n "$cred_home" ]] && seed_copy "$cred_seed" "$HOME/$cred_home"
done < <(jq -r '.items[] | [.home, .seed] | @tsv' "$CREDENTIALS_MANIFEST")

[[ -d "$WORKSPACE" ]] || { echo "seat-resident-shell: workspace missing: $WORKSPACE" >&2; exit 2; }
cd "$WORKSPACE" || exit 2

exec claude
