#!/usr/bin/env bash
# 从本机发布到 105 服务器 /root/wordloop
# 用法: ./deploy/publish.sh
#       ./deploy/publish.sh root@120.26.184.105
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SSH_TARGET="${1:-${SSH_TARGET:-root@120.26.184.105}}"

# 可选：deploy/secrets.env 覆盖数据库等变量
if [ -f "$ROOT/deploy/secrets.env" ]; then
  # shellcheck source=/dev/null
  source "$ROOT/deploy/secrets.env"
fi

MYSQL_HOST="${MYSQL_HOST:-rm-uf6h1j53vtuxi78i90o.mysql.rds.aliyuncs.com}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_USER="${MYSQL_USER:-boot}"
# %40 表示 @
MYSQL_PASSWORD="${MYSQL_PASSWORD:-@Abc888888}"
MYSQL_DATABASE="${MYSQL_DATABASE:-wordloop}"

echo ">>> 同步代码到 ${SSH_TARGET}:/root/wordloop/"
ssh -o ConnectTimeout=15 "$SSH_TARGET" "mkdir -p /root/wordloop"

rsync -avz --delete \
  --exclude 'backend/venv' \
  --exclude 'backend/__pycache__' \
  --exclude 'backend/.env' \
  --exclude 'backend/wordloop.db' \
  --exclude 'backend/data/cache' \
  --exclude 'frontend/node_modules' \
  --exclude '.git' \
  "$ROOT/" "${SSH_TARGET}:/root/wordloop/"

echo ">>> 远程安装与启动"
ssh "$SSH_TARGET" \
  "MYSQL_HOST='${MYSQL_HOST}' \
   MYSQL_PORT='${MYSQL_PORT}' \
   MYSQL_USER='${MYSQL_USER}' \
   MYSQL_PASSWORD='${MYSQL_PASSWORD}' \
   MYSQL_DATABASE='${MYSQL_DATABASE}' \
   bash /root/wordloop/deploy/install-production.sh"

echo ">>> 发布完成: http://120.26.184.105/ （Cloudflare 请将 w 解析到该 IP）"
