#!/usr/bin/env bash
# 增量部署。本地跑：bash scripts/deploy.sh [epsilon|alpha]
# 默认 epsilon（向后兼容无参调用）。

set -euo pipefail

HOST_ARG="${1:-epsilon}"

case "$HOST_ARG" in
    epsilon) TARGET_IP="112.124.27.213" ;;
    alpha)   TARGET_IP="120.27.148.143" ;;
    [0-9]*.*[0-9]*) TARGET_IP="$HOST_ARG" ;;  # 任意 IP，给 chaos migration drill 用
    *) echo "未知 host: $HOST_ARG（支持 epsilon | alpha | <IP>）" >&2; exit 1 ;;
esac

APP_DIR="/opt/xiangqin"

echo "[deploy:$HOST_ARG] [1/4] rsync 源码到 $TARGET_IP"
rsync -az --delete \
    --exclude '.venv' --exclude '__pycache__' --exclude '.pytest_cache' \
    --exclude 'data' --exclude '*.db*' --exclude '.git' \
    ./ "root@${TARGET_IP}:${APP_DIR}/"

echo "[deploy:$HOST_ARG] [2/4] 远端 uv sync (prod-only, 跳过 dev) + 建 logs 目录 + chown"
# --no-group dev: 生产不装 dev 依赖（genbadge/pillow/ruff/pytest 等），省磁盘 + 避免
# 小机器下载大包超时（pillow 6.8MB，UV_HTTP_TIMEOUT=30s 默认容易挂）
# UV_INDEX_URL：阿里云 ECS 走国内 PyPI 镜像，避免从 PyPI 境外 CDN 下载超时（M4/M6 drill 踩坑 2026-04-23）
# UV_HTTP_TIMEOUT=300：5 分钟，小机 1C1G + 境内镜像有时也慢
ssh "root@${TARGET_IP}" "cd ${APP_DIR} && \
    mkdir -p ${APP_DIR}/logs ${APP_DIR}/data && \
    UV_PYTHON_INSTALL_DIR=/opt/uv-python \
    UV_PYTHON_PREFERENCE=only-managed UV_PYTHON=3.12 \
    UV_HTTP_TIMEOUT=300 \
    UV_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ \
    /root/.local/bin/uv sync --no-group dev && \
    chown -R xiangqin:xiangqin ${APP_DIR}"

echo "[deploy:$HOST_ARG] [3/4] systemd unit"
ssh "root@${TARGET_IP}" "cp ${APP_DIR}/systemd/xiangqin.service /etc/systemd/system/ && systemctl daemon-reload && systemctl enable xiangqin"

echo "[deploy:$HOST_ARG] [4/4] 重启 + smoke test"
ssh "root@${TARGET_IP}" "systemctl restart xiangqin && sleep 2 && systemctl status --no-pager xiangqin"

echo "smoke test（内网 nginx，最多 15s 等 uvicorn ready）:"
ssh "root@${TARGET_IP}" 'for i in $(seq 1 15); do curl -sf http://127.0.0.1/health >/dev/null && break; sleep 1; done; curl -s http://127.0.0.1/health' && echo

echo "smoke test（外网，安全组未开则失败不阻断）:"
curl -s -m 3 "http://${TARGET_IP}/health" 2>/dev/null && echo || echo "  (外网不可达，可能 aliyun 安全组未开 80)"
