#!/bin/bash
# hzhub-portal-dealer 停止脚本

cd "$(dirname "$0")"

PID_FILE=".pid"

if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "Stopping hzhub-portal-dealer (PID: $PID)..."
        kill "$PID" 2>/dev/null
        sleep 2
        if ps -p "$PID" > /dev/null 2>&1; then
            echo "Force killing..."
            kill -9 "$PID" 2>/dev/null
        fi
        echo "hzhub-portal-dealer stopped."
    fi
    rm -f "$PID_FILE"
fi

# Fallback: kill by port
if ss -tlnp 2>/dev/null | grep -q ':5138 '; then
    echo "Port 5138 still in use, killing by port..."
    fuser -k 5138/tcp 2>/dev/null
    sleep 1
fi

if ! ss -tlnp 2>/dev/null | grep -q ':5138 '; then
    echo "hzhub-portal-dealer stopped."
else
    echo "hzhub-portal-dealer may still be running on port 5138."
fi
