#!/bin/bash
# Harness wrapper for externally isolated containers and native hosts.
#
# If $PWD is under /workspace/wolts/<name>/, set HOME to that wolt's root dir.
# This gives each wolt its own .claude/ config (settings, skills, sessions, history).
# Credentials are copied from shared on first run (not symlinked — Claude Code
# replaces files atomically on re-auth, which breaks symlinks).

if [ "${WOLTSPACE_ISOLATION:-external}" = "host" ]; then
    # Native mode inherits the user's real HOME and harness authentication.
    # Wolt identity is injected in the prepared boot prompt; this wrapper must
    # not copy credentials, pre-trust repositories, or mutate host config.
    exec claude "$@"
fi

WOLTSPACE_HOME_DIR="${WOLTSPACE_WOLT_HOME:-$(echo "$PWD" | sed -n 's|\(/workspace/wolts/[^/]*\).*|\1|p')}"
if [ -n "$WOLTSPACE_HOME_DIR" ] && [ -d "$WOLTSPACE_HOME_DIR/.claude" ]; then
    export HOME="$WOLTSPACE_HOME_DIR"
    # Claude Code auto-updates into $HOME/.local/bin. With a per-wolt HOME that dir
    # isn't on PATH, so the image's baked claude runs instead and warns about the
    # newer native install it can't reach. Put the wolt's own bin first.
    export PATH="$HOME/.local/bin:$PATH"
    # Self-heal missing credentials (copy from shared seed)
    WOLT_CREDS="$WOLTSPACE_HOME_DIR/.claude/.credentials.json"
    SHARED_CREDS="/workspace/wolts/.claude/.credentials.json"
    if [ ! -e "$WOLT_CREDS" ] && [ -f "$SHARED_CREDS" ]; then
        cp "$SHARED_CREDS" "$WOLT_CREDS"
    fi
fi

trust-dir "$(pwd)" 2>/dev/null
exec claude "$@"
