#!/usr/bin/env bash
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

resolve_real_codex() {
  local dir
  IFS=':' read -r -a path_parts <<<"${PATH}"
  for dir in "${path_parts[@]}"; do
    [[ "${dir}" == "${script_dir}" ]] && continue
    if [[ -x "${dir}/codex" ]]; then
      printf '%s\n' "${dir}/codex"
      return 0
    fi
  done
  return 1
}

codex_bin="$(resolve_real_codex)"
export HTTP_PROXY="${CLASH_HTTP_PROXY:-http://127.0.0.1:7890}"
export HTTPS_PROXY="${CLASH_HTTPS_PROXY:-http://127.0.0.1:7890}"
export ALL_PROXY="${CLASH_ALL_PROXY:-socks5://127.0.0.1:7890}"
export http_proxy="${HTTP_PROXY}"
export https_proxy="${HTTPS_PROXY}"
export all_proxy="${ALL_PROXY}"
export NO_PROXY="${CLASH_NO_PROXY:-localhost,127.0.0.1,::1}"
export no_proxy="${NO_PROXY}"

exec "${codex_bin}" "$@"
