#!/usr/bin/env bash
set -euo pipefail
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8

CONFIG_PATH="/root/.config/opencode/opencode.json"
TMP_PATH="${CONFIG_PATH}.tmp"

if [ -f "$CONFIG_PATH" ]; then
  echo "[entrypoint] Found $CONFIG_PATH — substituting {env:VAR} placeholders (best-effort)"
  python3.11 - <<'PY'
import re, os, sys
cfg = "/root/.config/opencode/opencode.json"
pat = re.compile(r'\{env:([A-Za-z0-9_]+)\}')
try:
    s = open(cfg, 'r', encoding='utf-8').read()
except Exception as e:
    sys.stderr.write(f"[entrypoint] ERROR reading config: {e}\n")
    sys.exit(1)

def rep(m):
    k = m.group(1)
    v = os.environ.get(k)
    if v is None:
        sys.stderr.write(f"[entrypoint] WARNING: env var {k} not set — leaving placeholder\n")
        return m.group(0)
    return v

new = pat.sub(rep, s)
open(cfg + ".tmp", 'w', encoding='utf-8').write(new)
print("[entrypoint] substitution done, wrote tmp file")
PY
  # Try to move tmp over original (works if mount writable)
  if mv -- "$CONFIG_PATH.tmp" "$CONFIG_PATH" 2>/dev/null; then
    echo "[entrypoint] Replaced original config with substituted version"
  else
    echo "[entrypoint] Could not overwrite mounted config (maybe read-only). Keeping substituted copy at $CONFIG_PATH.tmp"
  fi
else
  echo "[entrypoint] No config file at $CONFIG_PATH (you can mount ./opencode.json at runtime)"
fi

# Exec the given command (default: opencode start)
exec "$@"
