#!/usr/bin/env bash
# 增量部署到 epsilon。
# 从本地开发机运行：bash scripts/deploy.sh

set -euo pipefail

EPSILON_IP="${EPSILON_IP:-112.124.27.213}"
APP_USER="xiangqin"
APP_DIR="/opt/xiangqin"

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

echo "[2/4] 远端装 / 更新依赖 + 归属给 xiangqin 用户"
ssh "root@${EPSILON_IP}" "cd ${APP_DIR} && \
    UV_PYTHON_INSTALL_DIR=/opt/uv-python \
    UV_PYTHON_PREFERENCE=only-managed UV_PYTHON=3.12 \
    /root/.local/bin/uv sync && \
    chown -R xiangqin:xiangqin ${APP_DIR}"

echo "[3/4] 安装 / 更新 systemd unit"
ssh "root@${EPSILON_IP}" "cp ${APP_DIR}/systemd/xiangqin.service /etc/systemd/system/ && systemctl daemon-reload && systemctl enable xiangqin"

echo "[4/4] 重启服务"
ssh "root@${EPSILON_IP}" "systemctl restart xiangqin && sleep 2 && systemctl status --no-pager xiangqin"

echo "done. smoke test:"
curl -s "http://${EPSILON_IP}/health" && echo
