#!/usr/bin/env bash
#
# eic-mcp — run the EIC MCP servers installed in eic-shell as local HTTP
#           services for an LLM client (opencode, Claude Code, Copilot, …).
#           Service management only: it starts what the image ships
#           (/opt/local/bin) in native streamable-HTTP mode; it never
#           clones, builds, bridges, or fetches anything. A missing server
#           means the image is too old — upgrade eic-shell.
#
# Run it INSIDE eic-shell, or from the host: it finds your eic_xl .sif
# automatically (or set EIC_MCP_SIF).
#
#   eic-mcp list              # show the server registry
#   eic-mcp up                # start them (http://127.0.0.1:910x/mcp)
#   eic-mcp status            # which are listening
#   eic-mcp config CLIENT     # write CLIENT's MCP config file ('config CLIENT -' prints it)
#   eic-mcp logs NAME         # tail a server log
#   eic-mcp down | restart
#   eic-mcp docker-args       # docker run -p flags for the enabled servers (macOS)
#
# Pick which servers to run (default: uproot xrootd rucio):
#   EIC_MCP_SERVERS="uproot xrootd rucio" eic-mcp up
#
# Serve LLM clients on other machines (the servers have NO authentication):
#   EIC_MCP_HOST=0.0.0.0 eic-mcp up   # configs then advertise EIC_MCP_ADVERTISE_HOST
#
# macOS eic-shell is Docker: publish the server ports so a client on the Mac
# can reach them (inside Docker, eic-mcp binds all container interfaces itself):
#   DOCKER_OPTIONS="$(./eic-shell -- eic-mcp docker-args)" ./eic-shell
#
# Add your own / future EIC servers WITHOUT editing this file — drop a file in
#   ~/.config/eic-mcp/servers.d/<name>.conf
# that calls `register …` (see the built-ins below for the signature).
#
set -euo pipefail

# Needs bash 4+ (associative arrays); macOS ships 3.2, the container has bash 5.
if [ "${BASH_VERSINFO:-0}" -lt 4 ]; then
  echo "eic-mcp needs bash 4+ (macOS ships 3.2) — run it inside eic-shell: ./eic-shell, then eic-mcp up" >&2
  exit 1
fi

# ---- config -----------------------------------------------------------------
# State (servers, logs, pidfiles) lives in ~/.eic-mcp — but in the Docker eic_xl image (macOS
# eic-shell) $HOME=/root is wiped on exit, so anchor it to EIC_SHELL_PREFIX (on the host).
if [ -z "${EIC_MCP_STATE:-}" ] && [ "$HOME" = "/root" ] && [ -n "${EIC_SHELL_PREFIX:-}" ] \
   && [ -z "${APPTAINER_CONTAINER:-}${SINGULARITY_CONTAINER:-}" ]; then
  EIC_MCP_STATE="$(dirname "$EIC_SHELL_PREFIX")/.eic-mcp"
fi
EIC_MCP_STATE="${EIC_MCP_STATE:-$HOME/.eic-mcp}"
RUN_DIR="$EIC_MCP_STATE/run"; LOG_DIR="$EIC_MCP_STATE/logs"
BIND_HOST="${EIC_MCP_HOST:-127.0.0.1}"
EIC_MCP_SIF="${EIC_MCP_SIF:-}"
RUCIO_CFG="${RUCIO_CFG:-/opt/rucio/etc/rucio.cfg}"
CONF_DIR="${EIC_MCP_CONF_DIR:-$HOME/.config/eic-mcp/servers.d}"

# BIND_HOST is the real bind address; URL_HOST goes into client configs —
# the same, except 0.0.0.0 advertises EIC_MCP_ADVERTISE_HOST instead.
# Docker (macOS eic-shell): published ports (-p) reach the container's eth0,
# never its loopback, so bind everything there; the network is private and
# only the published ports on the host's loopback lead in.
if [ -z "${EIC_MCP_HOST:-}" ] && [ -f /.dockerenv ]; then
  BIND_HOST=0.0.0.0; URL_HOST=127.0.0.1
elif [ "$BIND_HOST" = "0.0.0.0" ]; then
  URL_HOST="${EIC_MCP_ADVERTISE_HOST:-$(hostname -I 2>/dev/null | awk '{print $1}' || true)}"
  URL_HOST="${URL_HOST:-127.0.0.1}"
  {
    echo "⚠ EIC_MCP_HOST=0.0.0.0 — the MCP servers have NO authentication and are"
    echo "  reachable by anything that can route to this host's 910x ports. Use only"
    echo "  on a trusted network (apptainer shares the host network namespace)."
  } >&2
else
  URL_HOST="$BIND_HOST"
fi

# ---- server registry --------------------------------------------------------
# register NAME PORT COMMAND REPO HTTP_TEMPLATE [ENV_HOOK]
#   HTTP_TEMPLATE runs the installed COMMAND as a streamable-HTTP service
#   (%c → command, %h → bind host, %p → port); EMPTY = stdio-only, `up` skips it.
#   ENV_HOOK is a function that echoes `export …` lines (auth/config).
declare -A SRV_PORT SRV_CMD SRV_REPO SRV_HTTP SRV_ENV
SRV_ORDER=()
register() {
  local n=$1
  SRV_PORT[$n]=$2; SRV_CMD[$n]=$3; SRV_REPO[$n]=$4
  SRV_HTTP[$n]=$5; SRV_ENV[$n]=${6:-}
  case " ${SRV_ORDER[*]:-} " in *" $n "*) :;; *) SRV_ORDER+=("$n");; esac
}

# --- per-server env hooks (echo shell `export` lines) ---
# Rucio: reuse the same shared read-only eicread account the CLI uses, straight
# from the container rucio.cfg. No user secrets.
rucio_env() {
  cat <<PY
eval "\$(python3 - <<'EOF'
import configparser, shlex
c = configparser.ConfigParser(); c.read("$RUCIO_CFG")
g = lambda k, d="": c.get("client", k, fallback=d)
print("export RUCIO_URL="       + shlex.quote(g("rucio_host", "https://rucio-server.jlab.org:443")))
print("export RUCIO_AUTH_TYPE=userpass")
print("export RUCIO_USERNAME="  + shlex.quote(g("username", "eicread")))
print("export RUCIO_PASSWORD="  + shlex.quote(g("password", "eicread")))
print("export RUCIO_ACCOUNT="   + shlex.quote(g("account",  g("username", "eicread"))))
print("export RUCIO_VO=")
EOF
)"
PY
}
# BNL disk serves current campaigns (25.12.0+); the JLab store stops at 25.10.x.
# For older data: XROOTD_SERVER=root://dtn-eic.jlab.org XROOTD_BASE_DIR=/volatile/eic/EPIC
xrootd_env() { echo "export XROOTD_SERVER='${XROOTD_SERVER:-root://epicxrd1.sdcc.bnl.gov:1095}' XROOTD_BASE_DIR='${XROOTD_BASE_DIR:-/eic/EPIC}'"; }
zenodo_env() { [ -n "${ZENODO_API_KEY:-}" ] && echo "export ZENODO_API_KEY='$ZENODO_API_KEY'" || echo ":"; }

# --- built-in EIC servers ---
register uproot 9101 uproot-mcp-server https://github.com/eic/uproot-mcp-server \
  '%c --transport http --host %h --port %p'
register xrootd 9102 xrootd-mcp-server https://github.com/eic/xrootd-mcp-server \
  'MCP_TRANSPORT=http MCP_HOST=%h MCP_PORT=%p %c' xrootd_env
register rucio  9103 rucio-eic-mcp     https://github.com/eic/rucio-eic-mcp-server \
  '%c --transport http --host %h --port %p' rucio_env
# stdio-only upstream — skipped by `up` until it gains an HTTP transport
register zenodo 9104 zenodo-mcp-server https://github.com/eic/zenodo-mcp-server \
  '' zenodo_env
# future: register indico 9105 indico-mcp-server https://github.com/cohm/indico-mcp \
#   '%c --transport http --host %h --port %p' indico_env

# --- load user / collaboration extensions ---
# shellcheck disable=SC1090  # user drop-ins are dynamic by design
if [ -d "$CONF_DIR" ]; then for f in "$CONF_DIR"/*.conf; do [ -e "$f" ] && source "$f"; done; fi

enabled_servers() { echo "${EIC_MCP_SERVERS:-uproot xrootd rucio}"; }

# ---- run inside the EIC software stack --------------------------------------
# apptainer markers, or /etc/eic-env.sh for the Docker eic_xl image (macOS)
in_container() { [ -n "${APPTAINER_CONTAINER:-}" ] || [ -n "${SINGULARITY_CONTAINER:-}" ] || [ -e /.singularity.d ] || [ -e /singularity ] || [ -e /etc/eic-env.sh ]; }
# Locate the eic_xl image the same way an eic-shell install lays it out:
# EIC_MCP_SIF (remembered), the last hit (cached), EIC_SHELL_PREFIX, the
# PREFIX= recorded in an eic-shell launcher (./eic-shell or on PATH), then
# $PWD and the quickstart default ~/eic. Any eic_xl-*.sif version counts.
# Last resort: the CVMFS nightly image (farms without a local install).
find_sif() {
  local cache="$EIC_MCP_STATE/sif" d s launcher
  if [ -n "$EIC_MCP_SIF" ]; then
    mkdir -p "$EIC_MCP_STATE"; printf '%s\n' "$EIC_MCP_SIF" >"$cache"
    echo "$EIC_MCP_SIF"; return
  fi
  if [ -f "$cache" ]; then
    s="$(cat "$cache")"; [ -e "$s" ] && { echo "$s"; return; }
  fi
  local prefixes=()
  [ -n "${EIC_SHELL_PREFIX:-}" ] && prefixes+=("$EIC_SHELL_PREFIX" "${EIC_SHELL_PREFIX%/local}")
  for launcher in "$PWD/eic-shell" "$(command -v eic-shell 2>/dev/null || true)"; do
    [ -n "$launcher" ] && [ -f "$launcher" ] && \
      prefixes+=("$(sed -n '/^PREFIX=/{s/^PREFIX=//;s/^"//;s/"$//;p;q}' "$launcher")")
  done
  prefixes+=("$PWD" "$HOME/eic")
  local cand
  for d in "${prefixes[@]}"; do
    [ -n "$d" ] || continue
    s=""
    for cand in "$d"/local/lib/eic_xl-*.sif "$d"/lib/eic_xl-*.sif; do   # newest match wins
      [ -e "$cand" ] || continue
      { [ -z "$s" ] || [ "$cand" -nt "$s" ]; } && s="$cand"
    done
    [ -n "$s" ] && { mkdir -p "$EIC_MCP_STATE"; printf '%s\n' "$s" >"$cache"; echo "$s"; return; }
  done
  # Unpacked directory image; apptainer runs it like a .sif.
  s="/cvmfs/singularity.opensciencegrid.org/eicweb/eic_xl:nightly"
  if [ -d "$s" ]; then
    echo "[eic-mcp] no local eic_xl .sif — using the CVMFS image $s" >&2
    mkdir -p "$EIC_MCP_STATE"; printf '%s\n' "$s" >"$cache"; echo "$s"; return
  fi
  echo ""
}
# Run in the EIC environment the way eic-shell/entrypoint.sh do: source
# /etc/eic-env.sh explicitly, with --norc --noprofile so user/system dotfiles
# can't perturb it (matches the container's deliberate no-dotfiles behaviour).
# EIC_MCP_EXTRA_PATH: prepend a host path to the container PATH (env vars
# survive `apptainer exec`; the host PATH does not).
# shellcheck disable=SC2016  # expands inside the container shell by design
ENV_PRELUDE='. /etc/eic-env.sh 2>/dev/null; case "${EIC_MCP_EXTRA_PATH:-}" in ?*) export PATH="$EIC_MCP_EXTRA_PATH:$PATH";; esac; '
sif_missing() { echo "ERROR: no eic_xl .sif found. macOS: eic-shell is Docker (no .sif) — run eic-mcp INSIDE ./eic-shell. Linux/WSL/farm: run from your eic-shell install dir, or set EIC_MCP_SIF once (it is remembered), e.g. EIC_MCP_SIF=/cvmfs/singularity.opensciencegrid.org/eicweb/eic_xl:nightly" >&2; }
run_in_env() {
  if in_container; then bash --norc --noprofile -c "$ENV_PRELUDE$1"; else
    local sif; sif="$(find_sif)"
    [ -z "$sif" ] && { sif_missing; exit 1; }
    apptainer exec "$sif" bash --norc --noprofile -c "$ENV_PRELUDE$1"
  fi
}
run_in_env_bg() {  # cmd pidfile logfile  — setsid → own process group for reliable stop
  local cmd="$1" pidfile="$2" logfile="$3" sif
  if in_container; then
    setsid bash --norc --noprofile -c "$ENV_PRELUDE$cmd" >"$logfile" 2>&1 </dev/null & echo $! >"$pidfile"
  else
    sif="$(find_sif)"; [ -z "$sif" ] && { sif_missing; return 1; }
    setsid apptainer exec "$sif" bash --norc --noprofile -c "$ENV_PRELUDE$cmd" >"$logfile" 2>&1 </dev/null & echo $! >"$pidfile"
  fi
}
# TCP connect test; always probe loopback (0.0.0.0 binds include it).
port_open() { timeout 2 bash -c "exec 3<>/dev/tcp/127.0.0.1/$1" 2>/dev/null; }
wait_ready() {  # name port timeout
  local name="$1" port="$2" timeout="${3:-60}" i pid
  pid="$(cat "$RUN_DIR/$name.pid" 2>/dev/null || true)"
  for ((i = 1; i <= timeout; i++)); do
    port_open "$port" && { echo "  ✓ $name ready on http://$URL_HOST:$port/mcp"; return 0; }
    # fail fast if the process we launched already died (e.g. bind failed)
    if [[ "$pid" =~ ^[0-9]+$ ]] && ! kill -0 "$pid" 2>/dev/null; then
      echo "  ✗ $name exited before binding $port (see: eic-mcp logs $name)" >&2; return 1
    fi
    sleep 1
  done
  echo "  ✗ $name did NOT come up on port $port within ${timeout}s (eic-mcp logs $name)" >&2; return 1
}
# enabled servers that are actually in the registry (warn + skip unknown names)
resolved_servers() {
  local n
  for n in $(enabled_servers); do
    if [ -n "${SRV_PORT[$n]:-}" ]; then echo "$n"
    else echo "eic-mcp: unknown server '$n' (not in registry) — skipping" >&2; fi
  done
}
# ... and of those, the ones with an HTTP template — a stdio-only server must
# never end up as a dead URL in a client config.
http_servers() {
  local n
  for n in $(resolved_servers); do [ -n "${SRV_HTTP[$n]}" ] && echo "$n"; done
  return 0
}

# ---- installed-only resolution ----------------------------------------------
require_server() {  # 0 iff server $1's command resolves inside the image
  local n=$1
  run_in_env "command -v '${SRV_CMD[$n]}' >/dev/null 2>&1" && return 0
  {
    echo "  ✗ $n: '${SRV_CMD[$n]}' is not installed in this eic_xl image."
    echo "      Your image is too old — upgrade it from your eic-shell directory:"
    echo "          ./eic-shell --upgrade"
    echo "      (or point eic-mcp at a local build with EIC_MCP_EXTRA_PATH=/path/to/bin)"
  } >&2
  return 1
}

# ---- run recipe ---------------------------------------------------------------
# Exports the server's env and execs it in native HTTP mode; the command is
# resolved with `command -v` INSIDE the container. The restart loop turns a
# crash into a 1s blip, but gives up after 5 immediate exits so a permanent
# misconfiguration fails fast into the log instead of burning wait_ready's 60s
# (a live loop PID defeats its dead-process fail-fast).
run_cmd() {  # echo the shell command that runs server $1 as an MCP-over-HTTP service
  local n=$1 port envfn env="" tmpl
  port=${SRV_PORT[$n]}; envfn=${SRV_ENV[$n]}
  [ -n "$envfn" ] && env="$($envfn) && "
  tmpl=${SRV_HTTP[$n]//%c/\"\$CMD\"}
  tmpl=${tmpl//%h/$BIND_HOST}
  tmpl=${tmpl//%p/$port}
  cat <<EOF
${env}CMD="\$(command -v '${SRV_CMD[$n]}')" && fails=0 && while :; do
  start=\$SECONDS
  $tmpl
  rc=\$?
  if [ \$((SECONDS - start)) -lt 5 ]; then fails=\$((fails + 1)); else fails=0; fi
  if [ \$fails -ge 5 ]; then
    echo "[eic-mcp] $n exited immediately 5 times (last status \$rc) — giving up" >&2
    exit \$rc
  fi
  echo "[eic-mcp] $n exited (\$rc) — restarting in 1s" >&2
  sleep 1
done
EOF
}

# ---- commands ---------------------------------------------------------------
cmd_list() {
  printf "%-8s %-6s %-20s %-11s %-8s %s\n" NAME PORT COMMAND TRANSPORT ENABLED REPO
  local en n e t; en=" $(enabled_servers) "
  for n in "${SRV_ORDER[@]}"; do
    case "$en" in *" $n "*) e=yes;; *) e=no;; esac
    [ -n "${SRV_HTTP[$n]}" ] && t=http || t=stdio-only
    printf "%-8s %-6s %-20s %-11s %-8s %s\n" "$n" "${SRV_PORT[$n]}" "${SRV_CMD[$n]}" "$t" "$e" "${SRV_REPO[$n]}"
  done
}
cmd_up() {
  mkdir -p "$RUN_DIR" "$LOG_DIR"
  echo "Starting EIC MCP servers (native streamable HTTP) ..."
  local n rc=0 opid; local -a launched=()
  for n in $(resolved_servers); do
    if [ -z "${SRV_HTTP[$n]}" ]; then
      echo "  • $n: no native HTTP transport upstream yet (stdio only) — skipping"
      continue
    fi
    # already running under our control? (live pidfile PID + port up) → skip
    opid="$(cat "$RUN_DIR/$n.pid" 2>/dev/null || true)"
    if [[ "$opid" =~ ^[0-9]+$ ]] && kill -0 "$opid" 2>/dev/null && port_open "${SRV_PORT[$n]}"; then
      echo "  • $n already running (pid $opid) — skipping"; continue
    fi
    # port held by an unrelated process → don't clobber it, report failure
    if port_open "${SRV_PORT[$n]}"; then
      echo "  ⚠ $n: port ${SRV_PORT[$n]} already in use by another process — not starting" >&2; rc=1; continue
    fi
    if ! require_server "$n"; then rc=1; continue; fi
    launched+=("$n")
  done
  for n in ${launched[@]+"${launched[@]}"}; do
    run_in_env_bg "$(run_cmd "$n")" "$RUN_DIR/$n.pid" "$LOG_DIR/$n.log"
  done
  [ ${#launched[@]} -gt 0 ] && echo "Waiting for servers ..."
  for n in ${launched[@]+"${launched[@]}"}; do wait_ready "$n" "${SRV_PORT[$n]}" 60 || rc=1; done
  echo
  [ "$rc" -eq 0 ] && echo "All servers up. Write your client's config with: eic-mcp config <client>" \
                  || echo "Some servers failed — check 'eic-mcp logs <name>'." >&2
  return $rc
}
stop_one() {
  local name="$1" pidfile="$RUN_DIR/$1.pid" port="${SRV_PORT[$1]:-}" pid i
  [ -z "$port" ] && { echo "  (unknown server $name)"; return; }
  if [ -f "$pidfile" ]; then
    pid="$(cat "$pidfile" 2>/dev/null || true)"
    if [[ "$pid" =~ ^[0-9]+$ ]]; then
      # kill the process group we started (setsid leader) — reliable and never
      # touches an unrelated process that merely happens to hold the port.
      kill -TERM -"$pid" 2>/dev/null || kill -TERM "$pid" 2>/dev/null || true
      for ((i = 0; i < 6; i++)); do port_open "$port" || break; sleep 1; done
      if port_open "$port"; then kill -KILL -"$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null || true; fi
    fi
    rm -f "$pidfile"
  fi
  if port_open "$port"; then
    echo "  ✗ $name: still listening on $port — could not stop (check 'eic-mcp logs $name' or kill it manually)" >&2
  else
    echo "  stopped $name"
  fi
}
cmd_down()   { echo "Stopping EIC MCP servers ..."; local n; for n in $(resolved_servers); do stop_one "$n"; done; }
cmd_status() {
  printf "%-8s %-30s %s\n" SERVER URL STATE
  local n st; for n in $(http_servers); do
    port_open "${SRV_PORT[$n]}" && st=UP || st=down
    printf "%-8s %-30s %s\n" "$n" "http://$URL_HOST:${SRV_PORT[$n]}/mcp" "$st"
  done
  echo "state: $EIC_MCP_STATE"
}
cmd_docker_args() {  # `docker run` flags: host loopback ports → the container's server ports
  local n out=""
  for n in $(http_servers); do out+="-p 127.0.0.1:${SRV_PORT[$n]}:${SRV_PORT[$n]} "; done
  echo "${out% }"
}
cmd_logs() {
  local n="${1:-}"; [ -z "$n" ] && { echo "usage: eic-mcp logs <name>" >&2; exit 2; }
  [ -n "${SRV_PORT[$n]:-}" ] || { echo "unknown server '$n' (see: eic-mcp list)" >&2; exit 2; }  # registered name only (no path traversal)
  exec tail -n 100 -f "$LOG_DIR/$n.log"
}
# `config CLIENT` writes an MCP client config pointing at the enabled servers'
# streamable-HTTP URLs, in the file that client actually reads:
#   opencode → opencode.jsonc (launch dir)   claude → .mcp.json
#   copilot  → ~/.copilot/mcp-config.json    vscode → .vscode/mcp.json  (CLI vs VS Code!)
#   cursor   → .cursor/mcp.json              gemini → .gemini/settings.json
#   codex    → ~/.codex/config.toml (appended)
# It never overwrites an existing file; `config CLIENT -` prints to stdout instead.
print_config() {
  local client="${1:-opencode}" n url first=1
  case "$client" in
    opencode)
      echo '{'
      # shellcheck disable=SC2016  # literal "$schema" JSON key
      echo '  "$schema": "https://opencode.ai/config.json",'
      echo '  "mcp": {'
      for n in $(http_servers); do
        url="http://$URL_HOST:${SRV_PORT[$n]}/mcp"
        [ $first -eq 1 ] || echo ','; first=0
        printf '    "%s": { "type": "remote", "url": "%s", "enabled": true }' "$n" "$url"
      done
      echo; echo '  }'; echo '}'
      ;;
    claude)   # Claude Code / Claude Desktop .mcp.json (project or ~/.claude.json)
      echo '{'; echo '  "mcpServers": {'
      for n in $(http_servers); do
        url="http://$URL_HOST:${SRV_PORT[$n]}/mcp"
        [ $first -eq 1 ] || echo ','; first=0
        printf '    "%s": { "type": "http", "url": "%s" }' "$n" "$url"
      done
      echo; echo '  }'; echo '}'
      ;;
    copilot)  # GitHub Copilot CLI ~/.copilot/mcp-config.json (preinstalled in eic-shell)
      echo '{'; echo '  "mcpServers": {'
      for n in $(http_servers); do
        url="http://$URL_HOST:${SRV_PORT[$n]}/mcp"
        [ $first -eq 1 ] || echo ','; first=0
        printf '    "%s": { "type": "http", "url": "%s", "tools": ["*"] }' "$n" "$url"
      done
      echo; echo '  }'; echo '}'
      ;;
    vscode)   # VS Code (Copilot Chat, Agent mode) .vscode/mcp.json
      echo '{'; echo '  "servers": {'
      for n in $(http_servers); do
        url="http://$URL_HOST:${SRV_PORT[$n]}/mcp"
        [ $first -eq 1 ] || echo ','; first=0
        printf '    "%s": { "type": "http", "url": "%s" }' "$n" "$url"
      done
      echo; echo '  }'; echo '}'
      ;;
    cursor)   # Cursor .cursor/mcp.json (transport inferred from the URL)
      echo '{'; echo '  "mcpServers": {'
      for n in $(http_servers); do
        url="http://$URL_HOST:${SRV_PORT[$n]}/mcp"
        [ $first -eq 1 ] || echo ','; first=0
        printf '    "%s": { "url": "%s" }' "$n" "$url"
      done
      echo; echo '  }'; echo '}'
      ;;
    gemini)   # Gemini CLI .gemini/settings.json (httpUrl = streamable HTTP; url would mean SSE)
      echo '{'; echo '  "mcpServers": {'
      for n in $(http_servers); do
        url="http://$URL_HOST:${SRV_PORT[$n]}/mcp"
        [ $first -eq 1 ] || echo ','; first=0
        printf '    "%s": { "httpUrl": "%s" }' "$n" "$url"
      done
      echo; echo '  }'; echo '}'
      ;;
    codex)    # Codex CLI ~/.codex/config.toml (TOML — append with >>)
      for n in $(http_servers); do
        echo "[mcp_servers.$n]"
        echo "url = \"http://$URL_HOST:${SRV_PORT[$n]}/mcp\""
      done
      ;;
    *) echo "unknown client '$client' (use: opencode | claude | copilot | vscode | cursor | gemini | codex)" >&2; exit 2 ;;
  esac
}
config_dest() {  # the file each client actually reads
  case "$1" in
    opencode) echo "opencode.jsonc" ;;
    claude)   echo ".mcp.json" ;;
    copilot)  echo "$HOME/.copilot/mcp-config.json" ;;
    vscode)   echo ".vscode/mcp.json" ;;
    cursor)   echo ".cursor/mcp.json" ;;
    gemini)   echo ".gemini/settings.json" ;;
    codex)    echo "$HOME/.codex/config.toml" ;;
    *) echo "unknown client '$1' (use: opencode | claude | copilot | vscode | cursor | gemini | codex)" >&2; return 2 ;;
  esac
}
write_client_config() {
  local client="$1" dest; dest="$(config_dest "$client")" || return 2
  case "$dest" in */*) mkdir -p "${dest%/*}";; esac
  if [ "$client" = codex ]; then   # TOML: append-only
    if [ -f "$dest" ] && grep -q "http://$URL_HOST:" "$dest"; then
      echo "  • $dest already lists the servers — left unchanged"
    else
      print_config codex >>"$dest"; echo "  ✓ appended the server entries to $dest"
    fi
  elif [ -e "$dest" ]; then
    echo "  • $dest exists — left unchanged (print with 'eic-mcp config $client -' and merge by hand)"
  else
    print_config "$client" >"$dest"
    case "$dest" in /*) echo "  ✓ wrote $dest";; *) echo "  ✓ wrote $PWD/$dest — launch $client in this directory";; esac
  fi
}
cmd_config() {  # write CLIENT's config in place; `config CLIENT -` prints to stdout
  local client="${1:-opencode}"
  config_dest "$client" >/dev/null || exit 2
  if [ "${2:-}" = "-" ]; then print_config "$client"; else write_client_config "$client"; fi
}

case "${1:-}" in
  list)    cmd_list ;;
  up)      cmd_up ;;
  down)    cmd_down ;;
  restart) cmd_down; sleep 1; cmd_up ;;
  status)  cmd_status ;;
  docker-args) cmd_docker_args ;;
  logs)    shift; cmd_logs "${1:-}" ;;
  config)  shift; cmd_config "${1:-opencode}" "${2:-}" ;;
  ""|-h|--help|help) awk 'NR > 1 && /^set -euo pipefail/ { exit } NR > 1 { sub(/^# ?/, ""); print }' "$0" ;;
  *) echo "Unknown command: $1" >&2; echo "Try: eic-mcp help" >&2; exit 2 ;;
esac
