#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PID_FILE="$REPO_ROOT/logs/web_dashboard.pid"

if [[ -f "$PID_FILE" ]]; then
  PID="$(cat "$PID_FILE" 2>/dev/null || true)"
  if [[ -n "$PID" ]] && kill -0 "$PID" 2>/dev/null; then
    kill "$PID" || true
    sleep 2
    if kill -0 "$PID" 2>/dev/null; then
      kill -9 "$PID" || true
    fi
    rm -f "$PID_FILE"
    echo "[OK] 已停止 dashboard (PID=$PID)"
    exit 0
  fi
fi

if command -v fuser >/dev/null 2>&1; then
  fuser -k 8765/tcp 2>/dev/null || true
fi

echo "[OK] dashboard 已停止（若原本未运行则无需处理）"
