#!/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
        PORT=$(netstat -tulnp 2>/dev/null | grep ":8082 " | grep "$PID" | awk '{print $4}' | cut -d: -f2)
        if [ -z "$PORT" ]; then
            PORT=$(ss -tulnp 2>/dev/null | grep ":8082 " | grep "pid=$PID" | awk '{print $5}' | cut -d: -f2)
        fi
        echo "hzhub-erp is running[1]."
        echo "  PID:  $PID"
        if [ -n "$PORT" ]; then
            echo "  Port: $PORT"
        else
            echo "  Port: 8082 (checking...)"
        fi
    else
        echo "hzhub-erp is not running (stale PID file: $PID)."
        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 "hzhub-erp is running[2]."
        echo "  PID:  $PID"
        echo "  Port: 8082"
    else
        echo "hzhub-erp is not running."
    fi
fi
