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

echo "=== 1. 谁在监听 19088 ==="
LP=$(ss -tlnp | grep 19088 | grep -oP 'pid=\K[0-9]+' | head -1)
echo "LISTEN_PID=$LP"
ls -l /proc/$LP/exe 2>/dev/null
ps -o pid,lstart,cmd -p $LP | tail -1 | cut -c1-160

echo ""
echo "=== 2. 二进制哈希对比 ==="
sha256sum /opt/friend-cluster/bin/friend-cluster 2>/dev/null
sha256sum /tmp/friend-cluster-manager-new 2>/dev/null || echo "NO_TMP_BINARY"

echo ""
echo "=== 3. 强制替换为本地新构建并精确重启 ==="
if [ -f /tmp/friend-cluster-manager-new ]; then
  PIDS=$(pgrep -x friend-cluster)
  echo "MGMT_PIDS=$PIDS"
  for p in $PIDS; do kill $p; done
  sleep 3
  pgrep -x friend-cluster && echo STILL_ALIVE || echo ALL_STOPPED
  cp /tmp/friend-cluster-manager-new /opt/friend-cluster/bin/friend-cluster
  chmod +x /opt/friend-cluster/bin/friend-cluster
  systemctl restart friend-cluster.service
  sleep 8
  NEWPID=$(ss -tlnp | grep 19088 | grep -oP 'pid=\K[0-9]+' | head -1)
  echo "NEW_LISTEN_PID=$NEWPID"
  curl -sS --max-time 10 http://127.0.0.1:19088/healthz
  echo
else
  echo "SKIP_REPLACE: /tmp/friend-cluster-manager-new 不存在"
fi

echo ""
echo "=== 4. 复测 panel-proxy 前缀剥离 ==="
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 400
echo ""
echo "=== 5. 实例侧收到的最新 path ==="
docker exec $C sh -c 'tail -5 /var/lib/friend/logs/friend.log' 2>/dev/null | grep "msg=request" | tail -3
echo DONE
