# verbose.sh — Verbose mode setup and API key masking/restore.
# shellcheck shell=bash
# Sourced by entrypoint.sh. Must be sourced before any other module
# that might produce set -x output.
# Copyright (c) 2026 Progralink. Licensed under the DevCage License — see LICENSE.

_VERBOSE=0
declare -A _SAVED_SECRETS=()

# _setup_verbose: enable verbose tracing with API key masking.
# Sets _VERBOSE=1 and enables set -x when SANDBOX_VERBOSE=1.
# Saves real API key values to _SAVED_SECRETS and replaces them with [MASKED].
_setup_verbose() {
    if [ "${SANDBOX_VERBOSE:-0}" = "1" ]; then
        _VERBOSE=1
        echo "entrypoint: verbose mode enabled (API keys masked in trace output)" >&2
        # Save and mask API keys/tokens to prevent leaking secrets via set -x trace.
        # Real values are restored before the final exec that hands off to the agent.
        local _mask_var _v
        for _mask_var in ANTHROPIC_API_KEY GEMINI_API_KEY GOOGLE_API_KEY OPENAI_API_KEY \
                         DEEPSEEK_API_KEY OPENROUTER_API_KEY COPILOT_GITHUB_TOKEN \
                         GH_TOKEN GITHUB_TOKEN CLAUDE_CODE_OAUTH_TOKEN; do
            _v="${!_mask_var:-}"
            if [ "$_v" != "" ]; then
                _SAVED_SECRETS[$_mask_var]="$_v"
                export "${_mask_var}=[MASKED]"
            fi
        done
        set -x
    fi
}

# _restore_secrets: restore masked API keys before exec-ing the agent.
# Must run AFTER touch /tmp/.devcage-ready but BEFORE exec.
_restore_secrets() {
    if [ "$_VERBOSE" = "1" ]; then
        set +x
        local _rk
        for _rk in "${!_SAVED_SECRETS[@]}"; do
            export "$_rk"="${_SAVED_SECRETS[$_rk]}"
        done
        unset _SAVED_SECRETS _rk
        set -x
    fi
}
