#!/usr/bin/env bash
# 停止宿主机模式进程
# shellcheck disable=SC1091
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
# shellcheck source=common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"

c_info "停止宿主机模式服务..."

stop_pidfile() {
  local name="$1"
  local f="$PID_DIR/$name.pid"
  if [[ -f "$f" ]]; then
    local pid
    pid="$(cat "$f")"
    if kill -0 "$pid" 2>/dev/null; then
      kill "$pid" 2>/dev/null || true
      sleep 0.3
      kill -9 "$pid" 2>/dev/null || true
    fi
    rm -f "$f"
  fi
}

for n in web gateway ai platform; do
  stop_pidfile "$n"
done

for port in 5173 8180 8001 8888; do
  if have_cmd fuser; then
    fuser -k "${port}/tcp" >/dev/null 2>&1 || true
  elif have_cmd lsof; then
    pids="$(lsof -t -iTCP:"$port" -sTCP:LISTEN 2>/dev/null || true)"
    [[ -n "$pids" ]] && kill $pids 2>/dev/null || true
  fi
done

if [[ "${1:-}" == "--with-db" ]]; then
  pg_ctl_bin="$(command -v pg_ctl 2>/dev/null || true)"
  if [[ -z "$pg_ctl_bin" ]]; then
    for d in /usr/lib/postgresql/*/bin /usr/pgsql-*/bin; do
      [[ -x "$d/pg_ctl" ]] && pg_ctl_bin="$d/pg_ctl" && break
    done
  fi
  if [[ -n "$pg_ctl_bin" && -f "$PGDATA/PG_VERSION" ]]; then
    "$pg_ctl_bin" -D "$PGDATA" stop -m fast || true
  fi
fi

c_ok "已停止。数据仍在: $RUNTIME"
