#!/bin/bash
set -e
BIN=/opt/friend-cluster/bin/friend-cluster
UNIT=friend-cluster.service

echo "=== 1. 停止 manager ==="
systemctl stop "$UNIT"
sleep 3
pgrep -f "bin/friend-cluster" && echo STILL_RUNNING || echo STOPPED

echo "=== 2. 替换二进制 ==="
cp "$BIN" "${BIN}.pre-trustfix-bak" 2>/dev/null || true
cp /tmp/friend-cluster-manager-new "$BIN"
chmod +x "$BIN"
echo REPLACED

echo "=== 3. 重启 manager ==="
systemctl start "$UNIT"
sleep 8
pgrep -f "bin/friend-cluster" > /dev/null && echo MANAGER_RUNNING || echo MANAGER_NOT_RUNNING

echo "=== 4. 验证 healthz ==="
sleep 3
curl -sS --max-time 10 http://127.0.0.1:19088/healthz | head -c 100
echo

echo "=== 5. 验证 manager 进程环境变量 ==="
MPID=$(pgrep -f "bin/friend-cluster" | head -1)
tr '\0' '\n' < /proc/$MPID/environ | grep TRUST || echo ENV_MISSING
echo DONE
