#!/bin/bash
# 一键停止所有 HZHub 服务

echo "========================================="
echo " 停止所有 HZHub 服务"
echo "========================================="

# 停止前端门户（先停前端，避免后端关闭时前端持续重连）
echo ""
echo "1️⃣  停止经销商门户 (hzhub-portal-dealer)..."
cd /data/hzhub/hzhub-portal-dealer
./stop.sh 2>/dev/null || { echo "脚本不存在，按端口清理..."; fuser -k 5138/tcp 2>/dev/null; }

echo ""
echo "2️⃣  停止员工门户 (hzhub-portal-employee)..."
cd /data/hzhub/hzhub-portal-employee
./stop.sh 2>/dev/null || { echo "按端口清理..."; fuser -k 5137/tcp 2>/dev/null; }

echo ""
echo "3️⃣  停止管理后台 (hzhub-admin)..."
cd /data/hzhub/hzhub-admin
./stop.sh 2>/dev/null || { echo "按端口清理..."; fuser -k 5666/tcp 2>/dev/null; }

# 停止后端服务
echo ""
echo "4️⃣  停止 API 网关 (hzhub-gateway)..."
cd /data/hzhub/hzhub-gateway
./stop.sh

echo ""
echo "5️⃣  停止 ERP 服务 (hzhub-erp)..."
cd /data/hzhub/hzhub-erp
./stop.sh

echo ""
echo "6️⃣  停止系统服务 (hzhub-system)..."
cd /data/hzhub/hzhub-system
./stop.sh

echo ""
echo "7️⃣  停止 AI 服务 (hzhub-ai)..."
cd /data/hzhub/hzhub-ai
./stop.sh

# 最终兜底：检查各端口是否仍有残留
echo ""
echo "🔍 检查端口残留..."
for port in 8080 8083 8082 6039 5666 5137 5138; do
    if ss -tlnp 2>/dev/null | grep -q ":$port "; then
        echo "  ⚠️  端口 $port 仍有进程占用，强制清理..."
        fuser -k $port/tcp 2>/dev/null
    fi
done

sleep 1

echo ""
echo "========================================="
echo " ✅ 所有服务停止流程完成"
echo "========================================="
echo ""
