#!/usr/bin/env bash
# Round 3(前情:probe_chromium_bisect.sh 证明 hardening 全部无罪,case 0 也崩;
# overcommit/ulimit 数据干净)。两件事:
#   1/2. 拿到崩溃的真实 FATAL 行 + gdb backtrace(此前日志被 head 截断,一直没见到)
#   3.   实测 Google 官方 chrome-headless-shell 在本宿主能否跑 —— 直接验证
#        「镜像弃发行版 chromium、改装 puppeteer pinned headless shell」修法的可行性
# 用法(服务器 repo 根): bash deploy/sandbox/probe_chromium_round3.sh [镜像名] [步骤]
#   步骤 = all(默认)/ 3(只跑第 3 步 headless-shell 实测)
set -u
IMG="${1:-zcbot-sandbox:latest}"
STEP="${2:-all}"

if [ "$STEP" = "all" ]; then
echo "===== 1. 崩溃日志尾部(找 FATAL/CHECK 行) ====="
docker run --rm --user zcbot -e HOME=/tmp --entrypoint bash "$IMG" -c '
  /usr/lib/chromium/chromium --no-sandbox --headless --disable-gpu --disable-dev-shm-usage \
      --enable-logging=stderr --v=1 --dump-dom about:blank >/tmp/c.log 2>&1; echo "rc=$?"
  echo "--- FATAL/CHECK grep ---"
  grep -aE "FATAL|Check failed|SIG|assert" /tmp/c.log | head -10
  echo "--- tail 30(去 dbus 噪音) ---"
  grep -aviE "dbus" /tmp/c.log | tail -30
  echo "--- cpu 安全特性 flags(pku/shstk/ibt,供对照) ---"
  grep -oE "pku|user_shstk|ibt" /proc/cpuinfo | sort -u | tr "\n" " "; echo'

echo
echo "===== 2. gdb backtrace(best-effort:apt 现装 gdb,网络不通自动跳过) ====="
docker run --rm --entrypoint bash "$IMG" -c '
  export DEBIAN_FRONTEND=noninteractive
  if apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq gdb >/dev/null 2>&1; then
    HOME=/tmp gdb -batch -ex run -ex "bt 12" \
      --args /usr/lib/chromium/chromium --no-sandbox --headless --disable-gpu \
      --disable-dev-shm-usage --dump-dom about:blank 2>&1 | grep -aviE "dbus" | tail -25
  else
    echo "[SKIP] apt 装 gdb 失败(容器网络不通?)"
  fi'
fi

echo
echo "===== 3. Google 官方 chrome-headless-shell 实测(验证修法 A) ====="
docker run --rm --user zcbot -e HOME=/tmp --entrypoint bash "$IMG" -c '
  set -u
  cd /tmp
  # npm 包源走阿里(npx 拉 @puppeteer/browsers 包本身)
  export npm_config_registry="https://registry.npmmirror.com"
  # 版本号从镜像内 puppeteer-core 锁定的 revisions 读 —— 不用 @stable:stable tag
  # 要先访问 Google 的 last-known-good 版本解析端点(被墙,上一轮三源全败的真因,
  # --base-url 只管二进制下载不管版本解析);pinned 版本还正好是 mermaid-cli CI
  # 实测过的那个。
  PC=/usr/local/lib/node_modules/@mermaid-js/mermaid-cli/node_modules/puppeteer-core
  VER=$(node -e "console.log(require(\"$PC/lib/cjs/puppeteer/revisions.js\").PUPPETEER_REVISIONS[\"chrome-headless-shell\"])" 2>/dev/null \
        || grep -rhoE "chrome-headless-shell.{0,4}[0-9]+\.[0-9.]+" "$PC/lib" 2>/dev/null | grep -oE "[0-9]+\.[0-9.]+" | head -1)
  [ -n "$VER" ] || { echo "[FAIL] 从 $PC 读不到 pinned 版本号"; exit 1; }
  echo "pinned chrome-headless-shell version: $VER"
  ok=""
  for BASE in "https://cdn.npmmirror.com/binaries/chrome-for-testing" \
              "https://registry.npmmirror.com/-/binary/chrome-for-testing"; do
    echo "[download] chrome-headless-shell@$VER base-url=$BASE ..."
    if npx -y @puppeteer/browsers install "chrome-headless-shell@$VER" \
          --path /tmp/pptr --base-url "$BASE" >/tmp/dl.log 2>&1; then
      ok=1; break
    fi
    grep -aE "Error|ENOTFOUND|ECONNRE|ETIMEDOUT|404|403" /tmp/dl.log | head -3
  done
  [ -n "$ok" ] || { echo "[FAIL] 阿里两个 binary 源都失败,完整日志尾部:"; tail -8 /tmp/dl.log; exit 1; }
  BIN=$(find /tmp/pptr -type f -name chrome-headless-shell | head -1)
  [ -n "$BIN" ] || { echo "[FAIL] 下载完成但没找到二进制"; exit 1; }
  echo "BIN=$BIN"
  "$BIN" --no-sandbox --disable-dev-shm-usage --dump-dom about:blank >/tmp/s.log 2>&1; rc=$?
  if [ $rc -eq 0 ]; then
    echo "[PASS] headless-shell 裸跑 rc=0"
  else
    echo "[FAIL] headless-shell 裸跑 rc=$rc"; grep -aviE "dbus" /tmp/s.log | tail -5
  fi
  printf "{\"executablePath\":\"%s\",\"args\":[\"--no-sandbox\",\"--disable-dev-shm-usage\"]}" "$BIN" > /tmp/pc.json
  printf "flowchart TB\n  A-->B\n" > /tmp/d.mmd
  if timeout 60 mmdc -i /tmp/d.mmd -o /tmp/d.png -p /tmp/pc.json >/tmp/m.log 2>&1 && [ -s /tmp/d.png ]; then
    echo "[PASS] mmdc + headless-shell 出图:"; ls -l /tmp/d.png
  else
    echo "[FAIL] mmdc + headless-shell 没出图"; tail -5 /tmp/m.log
  fi'

echo
echo "===== 判读 ====="
echo "3 两条 PASS           => 修法定案:Dockerfile 弃 apt chromium,build 时装 puppeteer pinned chrome-headless-shell"
echo "3 同样 SIGTRAP        => 宿主级问题(内核/CPU x 新版 chromium 通杀),看 1/2 的 FATAL 与 backtrace 再定"
echo "3 下载失败            => 网络问题,先解决容器出网/换 mirror 再跑"
