#!/bin/bash
# hzhub-gateway 停止脚本（改进版）
# 不依赖PID文件，直接通过进程名查找

cd "$(dirname "$0")"

echo "Stopping hzhub-gateway..."

# 方法1：通过进程名查找（不依赖PID文件）
PIDS=$(ps aux | grep '[h]zhub-gateway\|[h]zhub.gateway' | grep java | awk '{print $2}')

if [ -n "$PIDS" ]; then
    echo "Found gateway processes: $PIDS"

    for PID in $PIDS; do
        USER=$(ps -p $PID -o user --no-headers)
        echo "  Stopping PID $PID (user: $USER)..."

        if [ "$USER" = "root" ]; then
            # root进程需要sudo权限
            sudo kill -15 $PID 2>/dev/null || {
                echo "    ⚠️  需要sudo权限停止root进程 $PID"
                echo "    请手动执行: sudo kill -15 $PID"
            }
        else
            kill -15 $PID 2>/dev/null || {
                echo "    ⚠️  无法停止进程 $PID，可能需要权限"
            }
        fi
    done

    # 等待进程停止
    sleep 5

    # 检查是否还有进程
    REMAINING=$(ps aux | grep '[h]zhub-gateway\|[h]zhub.gateway' | grep java | awk '{print $2}')
    if [ -n "$REMAINING" ]; then
        echo "  Some processes still running, force killing..."
        for PID in $REMAINING; do
            USER=$(ps -p $PID -o user --no-headers)
            if [ "$USER" = "root" ]; then
                sudo kill -9 $PID 2>/dev/null || echo "    ⚠️  需sudo: sudo kill -9 $PID"
            else
                kill -9 $PID 2>/dev/null || echo "    ⚠️  杀不掉进程 $PID"
            fi
        done
    fi

    echo "✅ hzhub-gateway stopped."
else
    echo "ℹ️  No gateway process found."
fi

# 方法2：通过端口检测（兜底）
if ss -tlnp 2>/dev/null | grep -q ":8080 "; then
    echo "⚠️  Port 8080 still occupied, attempting cleanup..."
    fuser -k 8080/tcp 2>/dev/null || {
        echo "    Need sudo: sudo fuser -k 8080/tcp"
    }
    sleep 2
fi

# 清理PID文件（无论是否成功）
rm -f logs/gateway.pid

echo "Done."