#!/usr/bin/env bash
set -euo pipefail

REMOTE="${REMOTE:-daniel@10.0.0.5}"
APP_DIR="${APP_DIR:-/home/daniel/investor-rpg}"
SERVICE_NAME="${SERVICE_NAME:-investor-rpg}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOCAL_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
CONTENT_DIR="$(cd "${LOCAL_DIR}/.." && pwd)/content/raw/patterns"
STAMP="$(date +%Y%m%d-%H%M%S)"

echo "部署到 ${REMOTE}:${APP_DIR}"

ssh "${REMOTE}" "mkdir -p '${APP_DIR}/backups'; \
  if [ -f '${APP_DIR}/data.db' ]; then sqlite3 '${APP_DIR}/data.db' \".backup '${APP_DIR}/backups/data-${STAMP}.db'\" && chmod 600 '${APP_DIR}/backups/data-${STAMP}.db'; fi; \
  find '${APP_DIR}/backups' -type f -name 'data-*.db' -mtime +14 -delete 2>/dev/null || true"

rsync -az --delete \
  --exclude '.env' \
  --exclude 'data.db' \
  --exclude 'data.db-*' \
  --exclude 'config/ai/' \
  --exclude 'node_modules/' \
  --exclude 'dist/' \
  --exclude 'backups/' \
  --exclude '*.log' \
  --exclude '.DS_Store' \
  "${LOCAL_DIR}/" "${REMOTE}:${APP_DIR}/"

if [[ -d "${CONTENT_DIR}" ]]; then
  ssh "${REMOTE}" "mkdir -p '/opt/content/raw/patterns'"
  rsync -az --delete "${CONTENT_DIR}/" "${REMOTE}:/opt/content/raw/patterns/"
fi

ssh "${REMOTE}" "set -e; \
  cd '${APP_DIR}'; \
  npm ci; \
  npm run build; \
  find dist -type d -exec chmod 755 {} +; \
  find dist -type f -exec chmod 644 {} +; \
  sudo -n systemctl restart '${SERVICE_NAME}'; \
  sudo -n nginx -t; \
  curl -fsS --retry 10 --retry-connrefused --retry-delay 2 http://127.0.0.1:3000/api/health"

echo
echo "部署完成：http://${REMOTE#*@}/"
