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

cd "$(dirname "$0")"

PID_FILE="logs/system.pid"

if [ -f "$PID_FILE" ]; then
  PID=$(cat "$PID_FILE")
  if kill -0 "$PID" 2>/dev/null; then
    echo "Stopping hzhub-system (PID: $PID)..."
    kill "$PID"

    TIMEOUT=10
    while [ $TIMEOUT -gt 0 ]; do
      if ! kill -0 "$PID" 2>/dev/null; then
        echo "hzhub-system stopped."
        rm -f "$PID_FILE"
        exit 0
      fi
      sleep 1
      TIMEOUT=$((TIMEOUT - 1))
    done

    echo "Force killing..."
    kill -9 "$PID" 2>/dev/null
    echo "hzhub-system stopped."
    rm -f "$PID_FILE"
    exit 0
  fi
fi

PIDS=$(pgrep -f "hzhub-system\|HZHubSystemApplication" 2>/dev/null)
if [ -n "$PIDS" ]; then
  echo "Stopping hzhub-system (by name)..."
  kill $PIDS 2>/dev/null
  sleep 2
  echo "hzhub-system stopped."
else
  echo "hzhub-system is not running."
fi
