#!/usr/bin/env bash
# shellcheck shell=bash
set -euo pipefail

dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"

launcher_log_level=""
launcher_log_level_set=0
while (( $# > 0 )); do
    case "$1" in
        --log-level)
            if (( $# < 2 )); then
                echo "Usage: $0 [--log-level LEVEL] [codex-args...]" >&2
                exit 2
            fi
            launcher_log_level="$2"
            launcher_log_level_set=1
            shift 2
            ;;
        --log-level=*)
            launcher_log_level="${1#*=}"
            launcher_log_level_set=1
            shift
            ;;
        *)
            break
            ;;
    esac
done

if (( launcher_log_level_set )); then
    launcher_log_level="$(printf '%s' "$launcher_log_level" | tr '[:lower:]' '[:upper:]')"
    case "$launcher_log_level" in
        NOTSET|DEBUG|INFO|WARNING|ERROR|CRITICAL) ;;
        *)
            echo "Invalid log level '$launcher_log_level'; choose NOTSET, DEBUG, INFO, WARNING, ERROR, or CRITICAL." >&2
            exit 2
            ;;
    esac
    export EPHEMERAL_LOG_LEVEL="$launcher_log_level"
fi

# shellcheck source=/dev/null
source "$dir/ephemeral-session-env"

# Pass identity and startup settings through Codex's MCP configuration as well
# as the parent environment. This matters when Codex sanitizes child env vars.
# config.py owns the allowlist and TOML string escaping so the launcher and
# server use the same configuration vocabulary.
if [[ -x "$dir/ephemeral-config" ]]; then
    mcp_env_config="$("$dir/ephemeral-config" --codex-env-config)"
else
    mcp_env_config="$(python3 "$dir/config.py" --codex-env-config)"
fi

exec codex --config "$mcp_env_config" "$@"
