#!/usr/bin/env bash
# Memind 本地 → 105 全量同步（代码与 dist 一致；保留远端 .env 与 MindSpace 共享挂载）
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
EXCLUDE="${ROOT}/scripts/.rsync-exclude-105"
HOST="${H5_DEPLOY_HOST:-root@ssh105}"
REMOTE="${H5_REMOTE_DIR:-/root/tkmind_go/ui/h5}"
SERVICE="${H5_SYSTEMD_SERVICE:-goose-h5}"

echo "======================================"
echo "Memind → 105 同步"
echo "本地: ${ROOT}"
echo "远端: ${HOST}:${REMOTE}"
echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "======================================"

echo "==> rsync 代码 (--delete)..."
rsync -az --delete --exclude-from="${EXCLUDE}" "${ROOT}/" "${HOST}:${REMOTE}/"

echo "==> rsync dist..."
rsync -az "${ROOT}/dist/" "${HOST}:${REMOTE}/dist/"

echo "==> 远端 npm install..."
ssh -o BatchMode=yes "${HOST}" "cd '${REMOTE}' && npm install"

if [[ "${SKIP_BUILD:-0}" != 1 ]]; then
  echo "==> 远端 npm run build（失败不阻断，沿用已同步 dist）..."
  ssh -o BatchMode=yes "${HOST}" "cd '${REMOTE}' && npm run build" || echo "⚠️  远端 vite build 失败，已使用 rsync 的 dist/"
fi

if [[ "${NO_RESTART:-0}" != 1 ]]; then
  echo "==> 重启 ${SERVICE}..."
  ssh -o BatchMode=yes "${HOST}" "systemctl restart '${SERVICE}' && sleep 3 && systemctl is-active '${SERVICE}'"
fi

echo ""
echo "=== 校验 ==="
for f in server.mjs user-publish.mjs user-space.mjs mindspace-sandbox-mcp.mjs mindspace-page-edit-session.mjs package.json; do
  local_sum="$(openssl md5 "${ROOT}/${f}" 2>/dev/null | awk '{print $2}' \
    || md5 -q "${ROOT}/${f}" 2>/dev/null \
    || md5sum "${ROOT}/${f}" 2>/dev/null | awk '{print $1}')"
  remote_sum="$(ssh -o BatchMode=yes "${HOST}" "md5sum '${REMOTE}/${f}' 2>/dev/null | awk '{print \$1}'")"
  if [[ "${local_sum}" == "${remote_sum}" ]]; then
    echo "✓ ${f}"
  else
    echo "✗ ${f} 不一致 (local=${local_sum} remote=${remote_sum})" >&2
    exit 1
  fi
done

ssh -o BatchMode=yes "${HOST}" "curl -sf 'http://127.0.0.1:8080/api/status' && echo ' ← h5 ok'" || {
  echo "✗ 105 H5 健康检查失败" >&2
  exit 1
}

echo ""
echo "✅ 本地与 105 已同步"
