#!/bin/bash
BASE=http://10.168.3.36:19088
C=friend-deploy-20cc100e-c6e

echo "=== 1. 替换二进制并精确重启 ==="
PIDS=$(pgrep -x friend-cluster)
echo "OLD_PIDS=$PIDS"
for p in $PIDS; do kill $p; done
sleep 3
pgrep -x friend-cluster && echo STILL_ALIVE || echo ALL_STOPPED
cp /tmp/manager-fix-prefix /opt/friend-cluster/bin/friend-cluster
chmod +x /opt/friend-cluster/bin/friend-cluster
systemctl restart friend-cluster.service
sleep 8
curl -sS --max-time 10 http://127.0.0.1:19088/healthz
echo

echo "=== 2. 复测 panel-proxy（cookie + 实例 token）==="
ITOK=$(docker exec $C sh -c "grep api_auth_token /app/config/config.yaml" | awk '{print $2}')
RESP=$(curl -sS --max-time 10 -X POST -H "Authorization: Bearer dev-admin-token" -H "Content-Type: application/json" -d "{}" "$BASE/api/v1/instances/friend-3f527e57/tunnels")
TTOK=$(echo "$RESP" | python3 -c "import sys,json,urllib.parse as u; print(u.parse_qs(u.urlparse(json.load(sys.stdin)[\"url\"]).query)[\"__friend_tunnel\"][0])")
curl -sS --max-time 15 -w "\nHTTP=%{http_code}\n" -H "Cookie: friend_cluster_tunnel=$TTOK" -H "Authorization: Bearer $ITOK" "$BASE/panel/friend-3f527e57/api/chains" | head -c 500

echo ""
echo "=== 3. 实例侧收到的最新 path ==="
docker exec $C sh -c 'tail -5 /var/lib/friend/logs/friend.log' 2>/dev/null | grep "msg=request" | tail -3

echo "=== 4. WS Bridge 复测 ==="
python3 /tmp/m2_ws_verify.py 2>&1 | tail -15
echo DONE
