#!/usr/bin/env bash
# crypto_monitor_user 部署管理器 — 一键部署 / 卸载 / 更新
#
# 新服务器(免克隆):
#   curl -fsSL https://git.bz121.com/dekun/crypto_monitor_user/raw/branch/main/deploy/manage.sh | bash
#
# 已安装:
#   bash /opt/crypto_monitor_user/deploy/manage.sh
#
set -e
if [ -n "${BASH_VERSION:-}" ]; then
  set -o pipefail
fi

INSTALL_ROOT="${INSTALL_ROOT:-/opt/crypto_monitor_user}"
GIT_URL="${GIT_URL:-https://git.bz121.com/dekun/crypto_monitor_user.git}"
GIT_BRANCH="${GIT_BRANCH:-main}"

# curl | bash 时脚本从 stdin 执行,BASH_SOURCE[0] 为空;须先安全探测再 set -u
_script_src="${BASH_SOURCE[0]:-}"
if [[ -n "${_script_src}" && -f "${_script_src}" ]]; then
  DEPLOY_DIR="$(cd "$(dirname "${_script_src}")" && pwd)"
  REPO_ROOT="$(cd "${DEPLOY_DIR}/.." && pwd)"
  LIB_DIR="${DEPLOY_DIR}/lib"
else
  DEPLOY_DIR=""
  REPO_ROOT=""
  LIB_DIR=""
fi
unset _script_src

set -u

repo_ready() {
  [[ -f "${1}/deploy/setup_env.sh" && -f "${1}/deploy/manage.sh" ]]
}

sync_repo_if_present() {
  local root="$1"
  if [[ -d "${root}/.git" ]] && command -v git >/dev/null 2>&1; then
    git -C "${root}" pull -q --ff-only 2>/dev/null || true
  fi
}

bootstrap_repo() {
  if repo_ready "${INSTALL_ROOT}"; then
    REPO_ROOT="${INSTALL_ROOT}"
    DEPLOY_DIR="${REPO_ROOT}/deploy"
    LIB_DIR="${DEPLOY_DIR}/lib"
    sync_repo_if_present "${REPO_ROOT}"
    return 0
  fi
  if [[ -n "${REPO_ROOT}" ]] && repo_ready "${REPO_ROOT}"; then
    DEPLOY_DIR="${REPO_ROOT}/deploy"
    LIB_DIR="${DEPLOY_DIR}/lib"
    return 0
  fi

  echo "crypto_monitor_user 部署管理器 — 首次自举"
  echo "将克隆到: ${INSTALL_ROOT}"
  if [[ "$(id -u)" -ne 0 ]]; then
    echo "错误: 请使用 root 执行" >&2
    exit 1
  fi
  if ! command -v git >/dev/null 2>&1; then
    if command -v apt-get >/dev/null 2>&1; then
      export DEBIAN_FRONTEND=noninteractive
      apt-get update -qq
      apt-get install -y git ca-certificates curl
    else
      echo "错误: 未找到 git" >&2
      exit 1
    fi
  fi
  if [[ -d "${INSTALL_ROOT}" ]]; then
    echo "错误: ${INSTALL_ROOT} 已存在但不是有效仓库" >&2
    echo "请手动处理后再运行,或设置 INSTALL_ROOT 指向其它路径" >&2
    exit 1
  fi
  mkdir -p "$(dirname "${INSTALL_ROOT}")"
  git clone -b "${GIT_BRANCH}" "${GIT_URL}" "${INSTALL_ROOT}"
  # clone 后用仓库内脚本 + 终端 stdin(管道已 EOF)
  exec bash "${INSTALL_ROOT}/deploy/manage.sh" "$@" </dev/tty
}

show_banner() {
  local ip path
  path="${INSTALL_ROOT}"
  if repo_ready "${REPO_ROOT}"; then
    path="${REPO_ROOT}"
  fi
  # shellcheck source=/dev/null
  if [[ -f "${LIB_DIR}/common.sh" ]]; then
    source "${LIB_DIR}/common.sh"
    ip="$(detect_server_ip)"
  else
    ip="?"
  fi
  echo ""
  echo "╔══════════════════════════════════════╗"
  echo "║   crypto_monitor_user 部署管理器          ║"
  echo "║   路径: ${path}"
  echo "╚══════════════════════════════════════╝"
  echo ""
}

show_menu() {
  echo "  1) 一键部署(全套:三所+中控)"
  echo "  4) 仅 OKX 实例(不含中控)"
  echo "  5) 仅 Binance 实例(不含中控)"
  echo "  6) 仅 Gate 实例(不含中控)"
  echo "  2) 一键卸载"
  echo "  3) 更新"
  echo "  0) 退出"
  echo ""
}

main_menu() {
  bootstrap_repo
  # shellcheck source=lib/common.sh
  source "${LIB_DIR}/common.sh"
  REPO_ROOT="$(resolve_repo_root || echo "${INSTALL_ROOT}")"

  while true; do
    show_banner
    show_menu
    local choice=""
    cm_read choice "请选择 [0-6]: "
    case "${choice}" in
      1)
        bash "${LIB_DIR}/install.sh"
        ;;
      4)
        bash "${LIB_DIR}/install.sh" --exchange okx
        ;;
      5)
        bash "${LIB_DIR}/install.sh" --exchange binance
        ;;
      6)
        bash "${LIB_DIR}/install.sh" --exchange gate
        ;;
      2)
        bash "${LIB_DIR}/uninstall.sh"
        ;;
      3)
        bash "${LIB_DIR}/update.sh"
        ;;
      0)
        echo "再见."
        exit 0
        ;;
      *)
        echo "无效选项,请输入 0-6"
        ;;
    esac
    echo ""
    cm_read _ "按 Enter 返回菜单..."
  done
}

main_menu "$@"
