#!/bin/sh
# Contained wrapper around Codex CLI, first on the PATH in the contained/agent-codex
# image. It does two things the sandbox needs, then starts the real Codex.
#
# 1. The API key. Codex takes it from a login, not from the environment: a
#    key in OPENAI_API_KEY alone leaves Codex asking how to sign in. This
#    registers the key Contained passes — offline; Codex stores it in
#    ~/.codex/auth.json inside the sandbox's home volume.
# 2. The command sandbox. Codex sandboxes the commands it runs with
#    bubblewrap, which cannot create namespaces inside a container, so every
#    such command would fail. The Contained sandbox is the containment, so Codex
#    runs its commands directly unless the definition asks for a mode
#    itself. Codex's approval prompts are unaffected.
if [ -n "${OPENAI_API_KEY:-}" ]; then
    printenv OPENAI_API_KEY | /usr/local/bin/codex login --with-api-key >/dev/null 2>&1
fi

mode_given=no
for arg in "$@"; do
    case $arg in
        --sandbox|--sandbox=*|-s|--dangerously-bypass-approvals-and-sandbox|--full-auto)
            mode_given=yes
            break
            ;;
    esac
done

if [ "$mode_given" = no ]; then
    exec /usr/local/bin/codex --sandbox danger-full-access "$@"
fi
exec /usr/local/bin/codex "$@"
