#!/usr/bin/env bash
#
# DataOps Platform 停止脚本（Supervisor）
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# shellcheck source=dataops-common.sh
source "${SCRIPT_DIR}/dataops-common.sh"

stop_app() {
  echo_info "正在停止 ${APP_NAME}..."

  if ! pgrep -x supervisord >/dev/null 2>&1; then
    echo_warn "supervisord 未运行"
    if pgrep -f "${RUN_SCRIPT}" >/dev/null \
      || pgrep -f "gunicorn.*wsgi:application" >/dev/null; then
      echo_info "发现残留 Gunicorn 进程，正在终止..."
      pkill -f "${RUN_SCRIPT}" 2>/dev/null || true
      pkill -f "gunicorn.*wsgi:application" 2>/dev/null || true
    else
      echo_info "${APP_NAME} 未在运行"
    fi
    return 0
  fi

  local status
  status="$(supervisorctl status "${APP_NAME}" 2>/dev/null | awk '{print $2}' || echo "UNKNOWN")"

  if [[ "${status}" == "STOPPED" || "${status}" == "UNKNOWN" ]]; then
    echo_info "${APP_NAME} 已经停止"
    return 0
  fi

  supervisorctl stop "${APP_NAME}"
  sleep 2
  supervisorctl status "${APP_NAME}" || true
  echo_info "${APP_NAME} 已停止"
}

main() {
  echo "=========================================="
  echo "  DataOps Platform 停止脚本"
  echo "=========================================="

  if [[ "${EUID}" -ne 0 ]]; then
    echo_error "请使用 sudo 运行此脚本"
    exit 1
  fi

  stop_app
  echo ""
  echo_info "停止完成"
}

main "$@"
