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

cd "$(dirname "$0")"

PID_FILE="logs/erp.pid"

if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if kill -0 "$PID" 2>/dev/null; then
        echo "Stopping hzhub-erp (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-erp 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-erp 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-erp\|[h]zhub.erp' | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        echo "Stopping hzhub-erp (PID: $PID)..."
        kill "$PID"
        echo "hzhub-erp stopped."
    else
        echo "hzhub-erp is not running."
    fi
fi
