#!/bin/sh

set -eu
umask 077

api_key=${1-${OPENAI_API_KEY-}}
codex_dir="$HOME/.codex"

if [ -z "$api_key" ]; then
    if [ ! -t 0 ]; then
        echo "OPENAI_API_KEY is required." >&2
        exit 1
    fi

    printf 'Enter OPENAI_API_KEY: ' >&2
    saved_tty=$(stty -g)
    trap 'stty "$saved_tty" 2>/dev/null || true' 0 1 2 3 15
    stty -echo
    IFS= read -r api_key
    stty "$saved_tty"
    trap - 0 1 2 3 15
    printf '\n' >&2
fi

if [ -z "$api_key" ]; then
    echo "OPENAI_API_KEY cannot be empty." >&2
    exit 1
fi

case "$api_key" in
    *[!A-Za-z0-9._-]*)
        echo "OPENAI_API_KEY contains unsupported characters." >&2
        exit 1
        ;;
esac

mkdir -p "$codex_dir"
chmod 700 "$codex_dir"

config_tmp=$(mktemp "$codex_dir/.config.toml.XXXXXX")
auth_tmp=$(mktemp "$codex_dir/.auth.json.XXXXXX")
cleanup() {
    rm -f "$config_tmp" "$auth_tmp"
}
trap cleanup 0 1 2 3 15

cat > "$config_tmp" <<'EOF'
model_reasoning_effort = "xhigh"
disable_response_storage = true
network_access = "enabled"
windows_wsl_setup_acknowledged = true
model_context_window = 372000
model_auto_compact_token_limit = 344800


model_provider = "0029"
model = "gpt-5.6-terra"
review_model = "gpt-5.6-sol"

[model_providers.0029]
name = "0029"
base_url = "https://api.0029.org/v1"
wire_api = "responses"
requires_openai_auth = false

[features]
goals = true
js_repl = false
EOF

printf '{\n  "OPENAI_API_KEY": "%s"\n}\n' "$api_key" > "$auth_tmp"
chmod 600 "$config_tmp" "$auth_tmp"

mv -f "$config_tmp" "$codex_dir/config.toml"
mv -f "$auth_tmp" "$codex_dir/auth.json"
trap - 0 1 2 3 15

printf 'Overwrote: %s\n' "$codex_dir/config.toml"
printf 'Overwrote: %s\n' "$codex_dir/auth.json"

