#!/usr/bin/env bash
# QQ 机器人一键安装 / 更新脚本（Linux amd64 / arm64）
#
# 用法（在目标服务器上执行一条命令即可）：
#   curl -fsSL https://qqbot.zcy2116.top/install.sh | bash
#
# 本脚本安装与更新合一：
#   - 首次运行（目录里没有已安装实例）-> 全新安装
#   - 已安装过再运行                  -> 检查云端版本，有新版则更新
# 更新时只覆盖程序文件，凭证与数据目录（credentials/ data/ third_party/）
# 永不覆盖；更新后自动结束旧进程并启动新进程。
#
# 直连模式（离线 / 网盘分发，跳过云端清单）：
#   QQBOT_PKG_URL=https://.../qqbot-xxx.zip bash install.sh
#
# 常用环境变量：
#   INSTALL_DIR        安装目录（默认 /www/qqbot）
#   QQBOT_PUBLISH_BASE 发布端地址（默认 https://qqbot.zcy2116.top）
#   QQBOT_PKG_URL      直连安装包地址
#   QQBOT_YES=1        自动确认（免交互，适合脚本化）
#   QQBOT_QUIET=1      关闭详细日志
set -euo pipefail

# 发布端地址。可通过环境变量覆盖（一般无需改动）。
PUBLISH_BASE="${QQBOT_PUBLISH_BASE:-https://qqbot.zcy2116.top}"
# 安装目录。默认装在 /www/qqbot（宝塔等面板常见目录）；可用 INSTALL_DIR 显式指定。
INSTALL_DIR="${INSTALL_DIR:-/www/qqbot}"
# 直连模式：直接给定一个 zip 的下载地址，就跳过发布端清单查询。
PKG_URL_OVERRIDE="${QQBOT_PKG_URL:-}"
# 自动确认（免交互）。
ASSUME_YES="${QQBOT_YES:-0}"

# 更新时永不覆盖的用户数据目录（相对安装根）。
PROTECTED_DIRS=(credentials data third_party)
# 旧版本遗留、同样不覆盖的目录。
LEGACY_PROTECTED=(unz)

say()  { printf '%s\n' "$*"; }
warn() { printf '警告: %s\n' "$*" >&2; }
# 详细日志：始终输出到 stderr，便于排查。设置 QQBOT_QUIET=1 可关闭。
dbg()  { [ "${QQBOT_QUIET:-0}" = "1" ] || printf '  · %s\n' "$*" >&2; }
# 步骤标题，让日志有清晰分段。
step() { printf '\n[%s] %s   (已用 %ss)\n' "$1" "$2" "$(elapsed)"; }
# 脚本启动时间与已用秒数，便于观察进度、判断是否卡住。
T0="$(date +%s 2>/dev/null || echo 0)"
elapsed() {
  local now
  now="$(date +%s 2>/dev/null || echo 0)"
  printf '%s' "$((now - T0))"
}
# 进度行：简洁单行，适配手机窄屏 SSH 客户端。
progress() {
  if [ -t 2 ]; then
    printf '\r  ... %s' "$1" >&2
    printf '%-10s' '' >&2
  else
    printf '  ... %s\n' "$1" >&2
  fi
}
# 结束一行进度（配合 progress 使用）。
progress_end() {
  if [ -t 2 ]; then printf '\n' >&2; fi
  return 0
}
die() {
  printf '错误: %s\n' "$*" >&2
  printf '  · 脚本位置: %s:%s\n' "${BASH_SOURCE[0]:-install.sh}" "${BASH_LINENO[0]:-?}" >&2
  exit 1
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

# ---------------------------------------------------------------------------
# 通用：版本比较
# ---------------------------------------------------------------------------
# ver_cmp <a> <b>：a>b 输出 1，a<b 输出 -1，相等输出 0。
# 逐段按数字比较，支持纯数字（1、2、3）与 日期.N（20260114.0）两种格式。
ver_cmp() {
  local a="$1" b="$2"
  [ "$a" = "$b" ] && { printf '0'; return; }
  [ "$a" = "dev" ] && { printf -- '-1'; return; }
  [ "$b" = "dev" ] && { printf '1'; return; }
  local IFS=. i ai bi n
  local -a as bs
  read -r -a as <<< "$a"
  read -r -a bs <<< "$b"
  n=${#as[@]}
  [ ${#bs[@]} -gt "$n" ] && n=${#bs[@]}
  for ((i = 0; i < n; i++)); do
    ai="${as[i]:-0}"
    bi="${bs[i]:-0}"
    if [[ "$ai" =~ ^[0-9]+$ && "$bi" =~ ^[0-9]+$ ]]; then
      if [ "$((10#$ai))" -gt "$((10#$bi))" ]; then printf '1'; return; fi
      if [ "$((10#$ai))" -lt "$((10#$bi))" ]; then printf -- '-1'; return; fi
    else
      if [[ "$ai" > "$bi" ]]; then printf '1'; return; fi
      if [[ "$ai" < "$bi" ]]; then printf -- '-1'; return; fi
    fi
  done
  printf '0'
}

# ---------------------------------------------------------------------------
# 0. 选择安装位置 / 检测是否已安装
# ---------------------------------------------------------------------------
# 未显式指定 INSTALL_DIR 时，如果当前目录看起来已经是实例，就沿用当前目录。
if [ -z "${INSTALL_DIR:-}" ]; then
  if [ -f "$PWD/VERSION" ] && [ -x "$PWD/bin/qqbot" ]; then
    INSTALL_DIR="$PWD"
  else
    INSTALL_DIR="/www/qqbot"
  fi
fi

step 1 "环境检测"
os="$(uname -s 2>/dev/null || echo unknown)"
raw_arch="$(uname -m 2>/dev/null || echo unknown)"
printf '  -> 操作系统: %s\n' "$os"
printf '  -> CPU 架构: %s\n' "$raw_arch"
printf '  -> 安装目录: %s\n' "$INSTALL_DIR"

case "$os" in
  Linux) printf '  [OK] 系统为 Linux，支持安装\n' ;;
  *) printf '  [失败] 目前只支持 Linux，检测到的是 %s\n' "$os" >&2
     die "目前只支持 Linux，检测到的是 '$os'。Windows/macOS 请改用预编译包手动部署。" ;;
esac

case "$raw_arch" in
  x86_64|amd64)      arch="amd64" ;;
  aarch64|arm64)     arch="arm64" ;;
  *) printf '  [失败] 不支持的 CPU 架构 %s\n' "$raw_arch" >&2
     die "暂不支持的 CPU 架构 '$raw_arch'（只提供 linux/amd64 与 linux/arm64）。" ;;
esac
printf '  [OK] 架构识别为 linux/%s\n' "$arch"

# 下载与解压至少要有一个下载工具和一个解压工具。
if need_cmd curl; then
  DL="curl"
  printf '  [OK] 下载工具: curl\n'
elif need_cmd wget; then
  DL="wget"
  printf '  [OK] 下载工具: wget（未找到 curl）\n'
else
  printf '  [失败] 未找到 curl 或 wget\n' >&2
  die "缺少下载工具，请先安装 curl 或 wget。"
fi
if ! need_cmd unzip; then
  printf '  [失败] 未找到 unzip\n' >&2
  die "缺少解压工具 unzip，请先安装（Debian/Ubuntu: apt-get install -y unzip；CentOS: yum install -y unzip）。"
fi
printf '  [OK] 解压工具: unzip\n'

# sha256 命令探测：只用 command -v 判断可执行文件是否存在，绝不裸跑命令
# （裸跑 openssl 会进入交互模式导致脚本永久卡住）。
SHA_CMD=""
if command -v sha256sum >/dev/null 2>&1; then
  SHA_CMD="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
  SHA_CMD="shasum -a 256"
elif command -v openssl >/dev/null 2>&1; then
  SHA_CMD="openssl dgst -sha256"
fi
if [ -z "$SHA_CMD" ]; then
  warn "未找到 sha256 校验工具，将跳过完整性校验（不推荐）。"
else
  dbg "校验工具: $SHA_CMD"
fi

# 读取本地已安装版本。没有则视为全新安装。
local_version=""
if [ -f "$INSTALL_DIR/VERSION" ]; then
  local_version="$(tr -d '[:space:]' < "$INSTALL_DIR/VERSION" 2>/dev/null || true)"
fi
if [ -z "$local_version" ] && [ -f "$INSTALL_DIR/data/version.txt" ]; then
  local_version="$(tr -d '[:space:]' < "$INSTALL_DIR/data/version.txt" 2>/dev/null || true)"
fi

MODE="install"
if [ -x "$INSTALL_DIR/bin/qqbot" ] && [ -n "$local_version" ]; then
  MODE="update"
fi
printf '  [OK] 本机版本: %s（模式: %s）\n' "${local_version:-无}" "$([ "$MODE" = update ] && echo 更新 || echo 全新安装)"
say ">> 环境检测完成"

# ---------------------------------------------------------------------------
# 2. 获取目标版本（云端清单 / 直连）
# ---------------------------------------------------------------------------
pkg_url=""
pkg_sha=""
pkg_size=""
new_version=""
new_notes=""

if [ -n "$PKG_URL_OVERRIDE" ]; then
  # 直连模式：不经发布端清单，直接使用给定的 zip 下载地址。
  step 2 "直连模式"
  new_version="custom"
  pkg_url="$PKG_URL_OVERRIDE"
  say ">> 使用环境变量指定的安装包地址"
else
  step 2 "检查云端版本"
  manifest_url="${PUBLISH_BASE%/}/index.php?action=version"
  say ">> 正在连接发布端 ..."

  # 后台心跳：请求期间每秒刷新一次进度，避免看起来卡死。
  hb() {
    local i=0
    while :; do
      progress "等待发布端响应（最多 20s，可 Ctrl+C 中断）"
      i=$((i + 1))
      [ "$i" -ge 21 ] && break
      sleep 1
    done
    progress_end
  }
  hb &
  HB_PID=$!
  if [ "$DL" = "curl" ]; then
    manifest="$(curl -fsSL --connect-timeout 8 --max-time 20 "$manifest_url" 2>/dev/null || true)"
  else
    manifest="$(wget -q -T 20 -O - "$manifest_url" 2>/dev/null || true)"
  fi
  kill "$HB_PID" 2>/dev/null || true
  wait "$HB_PID" 2>/dev/null || true
  progress_end
  # 兼容配置了重写、直接用 /version.json 的发布端。
  if [ -z "$manifest" ]; then
    manifest_url="${PUBLISH_BASE%/}/version.json"
    printf '  [提示] 主接口无返回，自动回退备用接口\n'
    if [ "$DL" = "curl" ]; then
      manifest="$(curl -fsSL --connect-timeout 8 --max-time 20 "$manifest_url" 2>/dev/null || true)"
    else
      manifest="$(wget -q -T 20 -O - "$manifest_url" 2>/dev/null || true)"
    fi
  fi
  if [ -z "$manifest" ]; then
    printf '  [失败] 无法连接发布端或清单为空\n' >&2
    printf '  [提示] 若你只有网盘安装包，请用直连模式：\n' >&2
    printf '         QQBOT_PKG_URL="安装包zip地址" bash install.sh\n' >&2
    die "无法获取版本清单，请检查网络或发布端地址（$PUBLISH_BASE）。"
  fi
  printf '  [OK] 已获取清单（%s 字节）\n' "${#manifest}"

  # 极简 JSON 解析（不依赖 jq/python）：先取顶层 version / notes，
  # 再在 platforms 数组里按 os/arch 定位 url / sha256 / size。
  new_version="$(printf '%s' "$manifest" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
  if [ -z "$new_version" ]; then
    printf '  [失败] 发布端清单里版本号为空，说明发布端还没有可用版本\n' >&2
    die "版本清单里没有版本号。实际内容: $manifest"
  fi
  new_notes="$(printf '%s' "$manifest" | sed -n 's/.*"notes"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
  say ">> 云端最新版本: $new_version"
  if [ -n "$new_notes" ]; then
    printf '  更新内容: %s\n' "$new_notes"
  fi

  flat="$(printf '%s' "$manifest" | tr -d '\n\r')"
  IFS='{' read -r -a _blocks <<< "$flat"
  for blk in "${_blocks[@]}"; do
    case "$blk" in
      *'"arch"'*) : ;;
      *) continue ;;
    esac
    b_os="$(printf '%s' "$blk"   | sed -n 's/.*"os"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
    b_arch="$(printf '%s' "$blk" | sed -n 's/.*"arch"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
    if [ "$b_os" = "linux" ] && [ "$b_arch" = "$arch" ]; then
      pkg_url="$(printf '%s' "$blk"  | sed -n 's/.*"url"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
      pkg_sha="$(printf '%s' "$blk"  | sed -n 's/.*"sha256"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
      pkg_size="$(printf '%s' "$blk" | sed -n 's/.*"size"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/p' | head -n1)"
      break
    fi
  done

  if [ -z "$pkg_url" ]; then
    warn "清单中未找到 linux/$arch 对应的安装包，清单内容: $manifest"
    die "发布端没有 linux/$arch 的安装包。请确认该架构已发布，或换用其他架构的机器。"
  fi
fi

if [ -n "$pkg_size" ]; then
  if [ "$pkg_size" -ge 1048576 ]; then
    size_h="$((pkg_size/1024/1024))MB"
  elif [ "$pkg_size" -ge 1024 ]; then
    size_h="$((pkg_size/1024))KB"
  else
    size_h="${pkg_size}B"
  fi
  say ">> 目标版本 $new_version（linux/$arch, 约 $size_h）"
else
  say ">> 目标版本 $new_version（linux/$arch）"
fi
dbg "已解析目标安装包信息"
if [ -n "$pkg_sha" ]; then dbg "期望 sha256: $pkg_sha"; fi

# ---------------------------------------------------------------------------
# 2b. 更新模式下做版本对比，决定是否继续
# ---------------------------------------------------------------------------
if [ "$MODE" = "update" ] && [ -z "$PKG_URL_OVERRIDE" ]; then
  cmp="$(ver_cmp "$new_version" "$local_version")"
  if [ "$cmp" = "0" ]; then
    say ""
    say ">> 已经是最新版本（$local_version），无需更新。"
    if [ "$ASSUME_YES" != "1" ] && [ "${FORCE_REINSTALL:-0}" != "1" ]; then
      printf '>> 是否强制重新下载并覆盖安装？输入 y 继续，其他键退出: '
      ans=""
      if [ -t 0 ] && [ -t 1 ]; then IFS= read -r ans || ans=""
      elif { exec 4</dev/tty; } 2>/dev/null; then exec 4<&-; IFS= read -r ans < /dev/tty || ans=""; fi
      case "$ans" in y|Y|yes|YES) : ;; *) say "已取消。"; exit 0 ;; esac
    fi
  elif [ "$cmp" = "-1" ]; then
    say ""
    warn "云端版本（$new_version）比本机（$local_version）更旧或不兼容。"
    printf '>> 是否仍要降级覆盖？输入 y 继续，其他键退出: '
    ans=""
    if [ -t 0 ] && [ -t 1 ]; then IFS= read -r ans || ans=""
    elif { exec 4</dev/tty; } 2>/dev/null; then exec 4<&-; IFS= read -r ans < /dev/tty || ans=""; fi
    case "$ans" in y|Y|yes|YES) : ;; *) say "已取消。"; exit 0 ;; esac
  else
    say ""
    say ">> 发现新版本：$local_version  ->  $new_version"
    if [ -n "$new_notes" ]; then
      say ">> 本次更新内容："
      say "     $new_notes"
    fi
    if [ "$ASSUME_YES" != "1" ]; then
      printf '>> 是否现在更新？输入 y 更新，其他键退出: '
      ans=""
      if [ -t 0 ] && [ -t 1 ]; then IFS= read -r ans || ans=""
      elif { exec 4</dev/tty; } 2>/dev/null; then exec 4<&-; IFS= read -r ans < /dev/tty || ans=""; fi
      case "$ans" in y|Y|yes|YES) : ;; *) say "已取消更新。"; exit 0 ;; esac
    fi
  fi
fi

# ---------------------------------------------------------------------------
# 3. 下载 + 校验 + 解压
# ---------------------------------------------------------------------------
step 3 "下载并解压"
if [ ! -d /www ] && [ "$INSTALL_DIR" = "/www/qqbot" ]; then
  say ">> 未发现 /www 目录，将创建 /www/qqbot 作为安装位置"
else
  say ">> 安装位置: $INSTALL_DIR"
fi
mkdir -p "$INSTALL_DIR"

staging="$(mktemp -d -t qqbot-stage.XXXXXX)"
tmp_zip="$staging/pkg.zip"
staging_themed() {
  rm -rf "$staging" 2>/dev/null || true
}
trap 'staging_themed; rm -f "${tmp_zip:-}"' EXIT
dbg "临时目录: $staging"

if command -v df >/dev/null 2>&1; then
  avail="$(df -Pk "$INSTALL_DIR" 2>/dev/null | awk 'NR==2{print $4}')"
  if [ -n "$avail" ]; then dbg "安装目录可用空间: $((avail/1024))MB"; fi
fi

say ">> 正在下载安装包 ..."
# 后台心跳：每秒报告进度（已下载 KB / 百分比），适配手机窄屏。
dl_hb() {
  local cur=0 total_kb=0 pct=0
  if [ -n "$pkg_size" ] && [ "$pkg_size" -gt 0 ] 2>/dev/null; then
    total_kb=$((pkg_size / 1024))
  fi
  while :; do
    cur="$(wc -c < "$tmp_zip" 2>/dev/null | tr -d ' ' || echo 0)"
    cur="${cur:-0}"
    if [ "$total_kb" -gt 0 ]; then
      pct=$((cur / 1024 * 100 / total_kb))
      progress "已下载 $((cur/1024))KB / ${total_kb}KB  (${pct}%)"
    else
      progress "已下载 $((cur/1024))KB"
    fi
    sleep 1
  done
}
dl_hb &
DL_PID=$!
if [ "$DL" = "curl" ]; then
  # -s -S：不打印 curl 自带的 #### 长条（手机端会刷屏），只保留错误信息。
  curl -fL -sS --connect-timeout 15 -o "$tmp_zip" "$pkg_url"
  rc=$?
else
  wget -q --show-progress --progress=bar -T 60 -O "$tmp_zip" "$pkg_url"
  rc=$?
fi
kill "$DL_PID" 2>/dev/null || true
wait "$DL_PID" 2>/dev/null || true
progress_end
[ "$rc" -eq 0 ] || die "下载失败：无法获取安装包，请检查网络或安装包地址是否正确。"
printf '  [OK] 下载完成，文件大小: %s 字节\n' "$(wc -c < "$tmp_zip" 2>/dev/null || echo '?')"

if [ -n "$SHA_CMD" ] && [ -n "$pkg_sha" ]; then
  got="$($SHA_CMD "$tmp_zip" | awk '{print $1}')"
  dbg "实际 sha256: $got"
  if [ "$got" != "$pkg_sha" ]; then
    die "校验失败：下载文件与发布端不一致，已终止（可能是网络损坏或遭篡改）。"
  fi
  say ">> sha256 校验通过"
elif [ -n "$pkg_sha" ]; then
  warn "本机无 sha256 工具，跳过校验（期望值 $pkg_sha）"
else
  dbg "清单未提供 sha256，跳过校验"
fi

say ">> 解压到临时目录 ..."
unzip -oq "$tmp_zip" -d "$staging/new" || die "解压失败。"
# 兼容压缩包内带一层顶层目录的情况。
new_root="$staging/new"
if [ ! -f "$new_root/bin/qqbot" ]; then
  cand="$(find "$staging/new" -maxdepth 2 -type f -name qqbot -path '*/bin/*' 2>/dev/null | head -n1)"
  if [ -n "$cand" ]; then new_root="$(cd "$(dirname "$cand")/.." && pwd)"; fi
fi
[ -f "$new_root/bin/qqbot" ] || die "压缩包内未找到 bin/qqbot，安装包可能损坏。"
printf '  [OK] 解压完成（包内版本: %s）\n' "$(tr -d '[:space:]' < "$new_root/VERSION" 2>/dev/null || echo '?')"

# ---------------------------------------------------------------------------
# 4. 覆盖安装（保护 credentials/ data/ third_party/）
# ---------------------------------------------------------------------------
step 4 "部署文件"
mkdir -p "$INSTALL_DIR"

# 记录旧进程（若有），更新完成后需要重启。
# 安全约束：只匹配本安装目录下、以绝对路径启动的进程，绝不使用宽泛匹配，
# 避免误杀同一台机器上其他目录里运行的实例。
old_pids=""
if command -v pgrep >/dev/null 2>&1; then
  installed_bin="$INSTALL_DIR/bin/qqbot"
  if [ -x "$installed_bin" ]; then
    # pgrep -f 用绝对路径匹配；再用 /proc 校验 cmdline 确实指向本目录。
    for p in $(pgrep -f "$installed_bin" 2>/dev/null || true); do
      if [ -r "/proc/$p/cmdline" ]; then
        cl="$(tr '\0' ' ' < "/proc/$p/cmdline" 2>/dev/null || true)"
        case "$cl" in
          *"$installed_bin"*) old_pids="$old_pids $p" ;;
        esac
      fi
    done
  fi
fi
old_pids="$(printf '%s' "$old_pids" | tr -s ' ' | sed 's/^ //')"

copy_new() {
  local src="$1" dst="$2"
  if command -v rsync >/dev/null 2>&1; then
    local -a ex=()
    local d
    for d in "${PROTECTED_DIRS[@]}" "${LEGACY_PROTECTED[@]}"; do ex+=(--exclude "$d/"); done
    rsync -a --delete "${ex[@]}" --exclude 'credentials/' --exclude 'data/' --exclude 'third_party/' "$src"/ "$dst"/
  else
    # 无 rsync 的降级方案：逐个文件复制，跳过受保护目录。
    (
      cd "$src" || exit 1
      find . -type f -print0 | while IFS= read -r -d '' rel; do
        skip=0
        for d in "${PROTECTED_DIRS[@]}" "${LEGACY_PROTECTED[@]}"; do
          case "$rel" in ./"$d"/*) skip=1 ;; esac
        done
        [ "$skip" = 1 ] && continue
        dest="$dst/${rel#./}"
        mkdir -p "$(dirname "$dest")"
        cp -f "$rel" "$dest"
      done
    )
  fi
}

say ">> 部署程序文件（保留 credentials/ data/ third_party/）..."
copy_new "$new_root" "$INSTALL_DIR"
[ -f "$INSTALL_DIR/bin/qqbot" ] || die "部署后未找到 bin/qqbot。"
chmod +x "$INSTALL_DIR/bin/qqbot" 2>/dev/null || true
if [ -f "$INSTALL_DIR/start.sh" ]; then chmod +x "$INSTALL_DIR/start.sh" 2>/dev/null || true; fi
# 写入/更新版本文件，作为本机版本的权威来源。
# 优先采用云端清单里的版本号（维护者发布的权威版本）；清单没有时回退包内 VERSION。
if [ -n "$new_version" ] && [ "$new_version" != "custom" ]; then
  printf '%s\n' "$new_version" > "$INSTALL_DIR/VERSION"
elif [ -f "$new_root/VERSION" ]; then
  cp -f "$new_root/VERSION" "$INSTALL_DIR/VERSION" 2>/dev/null || \
    printf '%s\n' "$(tr -d '[:space:]' < "$new_root/VERSION")" > "$INSTALL_DIR/VERSION"
fi
say ">> 文件部署完成，本机版本更新为 $(tr -d '[:space:]' < "$INSTALL_DIR/VERSION" 2>/dev/null || echo '未知')"

# ---------------------------------------------------------------------------
# 5. 首次安装时引导配置（更新时跳过，配置已存在）
# ---------------------------------------------------------------------------
creds_dir="$INSTALL_DIR/credentials"
mkdir -p "$creds_dir"
chmod 700 "$creds_dir" 2>/dev/null || true

interactive=0
if [ "$MODE" = "install" ]; then
  step 5 "配置"
  if [ -t 0 ] && [ -t 1 ]; then
    interactive=1
    dbg "检测到交互终端，将引导填写配置"
  elif { exec 3</dev/tty; } 2>/dev/null; then
    exec 3<&-
    interactive=2
    dbg "检测到控制终端 /dev/tty，将引导填写配置"
  else
    dbg "无可用终端，跳过交互配置（稍后手动填写 credentials/ 下的文件）"
  fi

  # 读取已存在的凭据值：已填写过真实值就跳过该步，绝不覆盖用户配置。
  # 用 tr 去掉换行后按 key 提取，避免依赖 python/jq。
  read_json_val() {
    local file="$1" key="$2"
    [ -f "$file" ] || return 0
    tr -d '\n' < "$file" 2>/dev/null | \
      sed -n "s/.*\"$key\"[[:space:]]*:[[:space:]]*\"\([^\"\\]*\)\".*/\1/p"
  }
  # 占位符/空值视为未配置（与程序内 PlaceholderValue 判定一致）。
  is_real() {
    local v="$1"
    [ -n "$v" ] || return 1
    case "$v" in
      "在这里填写"*) return 1 ;;
      "change-me") return 1 ;;
    esac
    return 0
  }

  json_escape() {
    printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/\\t/g'
  }

  existing_qq_id="$(read_json_val "$creds_dir/qq.json" app_id)"
  existing_qq_secret="$(read_json_val "$creds_dir/qq.json" app_secret)"
  existing_llm_key="$(read_json_val "$creds_dir/llm.json" api_key)"
  existing_llm_base="$(read_json_val "$creds_dir/llm.json" base_url)"
  existing_llm_model="$(read_json_val "$creds_dir/llm.json" model)"
  existing_panel_pw="$(read_json_val "$creds_dir/panel.json" password)"

  qq_id=""; qq_secret=""; llm_key=""; llm_base=""; llm_model=""; panel_pw=""

  if [ "$interactive" != 0 ]; then
    say ""
    say "=============================================================="
    say "  配置机器人（直接回车 = 跳过该项）"
    say "  本机已填写过的项会自动跳过，不会被覆盖。"
    say "  输入会明文显示，方便你核对。"
    say "  跳过的项稍后可在 $creds_dir 里手动填写。"
    say "=============================================================="
  fi

  # 逐项处理：已配置则沿用并跳过；否则明文提示输入。
  # LAST_INPUT=1 表示本次确实输入了新值（用于决定是否重写该文件）。
  field() {
    local tag="$1" existing="$2" name="$3" line=""
    LAST_INPUT=0
    if is_real "$existing"; then
      if [ "$interactive" != 0 ]; then say "  $tag 已配置，跳过"; fi
      printf -v "$name" '%s' "$existing"
      return
    fi
    if [ "$interactive" = 0 ]; then printf -v "$name" '%s' ""; return; fi
    local prompt="$tag: "
    if [ "$interactive" = 2 ]; then
      printf '%s' "$prompt" > /dev/tty
      IFS= read -r line < /dev/tty || line=""
    else
      read -rp "$prompt" line || line=""
    fi
    [ -n "$line" ] && LAST_INPUT=1
    printf -v "$name" '%s' "$line"
  }

  qq_input=0; llm_input=0; panel_input=0
  field "1/6 QQ 机器人 AppID（回车跳过）"                      "$existing_qq_id"     qq_id;     [ "$LAST_INPUT" = 1 ] && qq_input=1
  field "2/6 QQ 机器人 AppSecret（回车跳过）"                   "$existing_qq_secret" qq_secret; [ "$LAST_INPUT" = 1 ] && qq_input=1
  field "3/6 大模型 API Key（回车跳过）"                        "$existing_llm_key"   llm_key;   [ "$LAST_INPUT" = 1 ] && llm_input=1
  field "4/6 大模型 Base URL（回车用默认）"                      "$existing_llm_base"  llm_base;  [ "$LAST_INPUT" = 1 ] && llm_input=1
  field "5/6 大模型模型名（回车用默认）"                          "$existing_llm_model" llm_model; [ "$LAST_INPUT" = 1 ] && llm_input=1
  field "6/6 面板登录密码（回车用默认）"                          "$existing_panel_pw"  panel_pw;  [ "$LAST_INPUT" = 1 ] && panel_input=1
  if [ "$interactive" != 0 ]; then
    say "如需指定机器人管理员，可在安装完成后编辑 $creds_dir/admins.json。"
  fi

  ph_qq_id="在这里填写你的 AppID"
  ph_qq_secret="在这里填写你的 AppSecret"
  ph_llm_key="在这里填写大模型 API Key"
  : "${llm_base:=https://api.deepseek.com/v1}"
  : "${llm_model:=deepseek-chat}"
  : "${panel_pw:=change-me}"

  write_file() {
    local path="$1" content="$2" force="${3:-0}"
    if [ -f "$path" ] && [ "$force" != "1" ]; then
      say ">> 已存在 $path，保留不覆盖。"
      return
    fi
    umask 077
    printf '%s' "$content" > "$path"
    chmod 600 "$path" 2>/dev/null || true
    dbg "已写入 $path (0600)"
  }

  qq_content_ok=1
  if [ -z "$qq_id" ] || [ -z "$qq_secret" ]; then qq_content_ok=0; fi
  write_file "$creds_dir/qq.json" "{
  \"app_id\": \"$(json_escape "${qq_id:-$ph_qq_id}")\",
  \"app_secret\": \"$(json_escape "${qq_secret:-$ph_qq_secret}")\"
}
" "$qq_input"
  if [ -z "$llm_key" ]; then llm_key="$ph_llm_key"; fi
  write_file "$creds_dir/llm.json" "{
  \"api_key\": \"$(json_escape "$llm_key")\",
  \"base_url\": \"$(json_escape "$llm_base")\",
  \"model\": \"$(json_escape "$llm_model")\",
  \"temperature\": \"0.7\",
  \"max_tokens\": \"4096\"
}
" "$llm_input"
  write_file "$creds_dir/admins.json" "[]"
  write_file "$creds_dir/panel.json" "{
  \"password\": \"$(json_escape "$panel_pw")\"
}
" "$panel_input"
  config_ready=0
  if [ "$qq_content_ok" = 1 ] && [ "$llm_key" != "$ph_llm_key" ]; then config_ready=1; fi
fi

# ---------------------------------------------------------------------------
# 6. 重启服务：结束旧进程，启动新进程
# ---------------------------------------------------------------------------
step 6 "完成"
say ">> 安装位置: $INSTALL_DIR"
if [ "$MODE" = "update" ]; then
  say ">> 更新完成：$local_version -> $(tr -d '[:space:]' < "$INSTALL_DIR/VERSION" 2>/dev/null || echo "$new_version")"
else
  say ">> 已生成配置:"
  ls -1 "$creds_dir" 2>/dev/null | sed 's/^/     /' || true
fi
say ""

# 结束旧进程（仅限本安装目录下的进程，避免误杀）。
if [ -n "$old_pids" ]; then
  say ">> 正在结束旧进程: $(echo "$old_pids" | tr '\n' ' ')"
  for p in $old_pids; do kill "$p" 2>/dev/null || true; done
  sleep 1
  for p in $old_pids; do kill -9 "$p" 2>/dev/null || true; done
fi

do_start=0
if [ "$ASSUME_YES" = "1" ]; then
  do_start=1
else
  printf '>> 是否现在启动机器人？输入 y 启动，其他键退出: '
  ans=""
  if [ -t 0 ] && [ -t 1 ]; then
    IFS= read -r ans || ans=""
  elif { exec 4</dev/tty; } 2>/dev/null; then
    exec 4<&-
    IFS= read -r ans < /dev/tty || ans=""
    printf '\n' > /dev/tty
  else
    say "（无交互终端，默认不自动启动）"
  fi
  case "$ans" in y|Y|yes|YES) do_start=1 ;; esac
fi

if [ "$do_start" = 1 ]; then
  if [ "$MODE" = "install" ] && [ "${config_ready:-1}" = 0 ]; then
    say ">> 配置未填全，启动后程序会提示你先填写占位符配置。"
  fi
  say ">> 正在启动机器人（按 Ctrl+C 停止）..."
  say ""
  cd "$INSTALL_DIR"
  exec "$INSTALL_DIR/start.sh"
else
  say ""
  say "已就绪但未启动。需要时执行："
  say "  cd $INSTALL_DIR && ./start.sh"
  if [ "$MODE" = "install" ] && [ "${config_ready:-1}" = 0 ]; then
    say ""
    say "提示：程序启动时若检测到占位符会明确报错并退出，按提示改完再跑即可。"
  fi
fi
