#!/bin/bash
# hzhub-gateway 停止脚本

cd "$(dirname "$0")"

PID_FILE="logs/gateway.pid"

if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if kill -0 "$PID" 2>/dev/null; then
        echo "Stopping hzhub-gateway (PID: $PID)..."
        kill "$PID"
        # Wait up to 10 seconds for graceful shutdown
        for i in $(seq 1 10); do
            if ! kill -0 "$PID" 2>/dev/null; then
                echo "hzhub-gateway stopped."
                rm -f "$PID_FILE"
                exit 0
            fi
            sleep 1
        done
        echo "Process did not stop gracefully, force killing..."
        kill -9 "$PID" 2>/dev/null
        rm -f "$PID_FILE"
        echo "hzhub-gateway force stopped."
    else
        echo "Process $PID is not running, cleaning up PID file."
        rm -f "$PID_FILE"
    fi
else
    # Fallback: find by process name
    PID=$(ps aux | grep '[h]zhub-gateway\|[h]zhub.gateway' | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        echo "Stopping hzhub-gateway (PID: $PID)..."
        kill "$PID"
        echo "hzhub-gateway stopped."
    else
        echo "hzhub-gateway is not running."
    fi
fi
