#!/bin/bash
# 管理会计OS — 一键拉取、构建并部署到生产
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "===== 管理会计OS 生产部署 ====="
echo ""

# 0. 拉取最新代码
echo "[0/4] 拉取最新代码..."
cd "$SCRIPT_DIR"
git pull origin main
echo "    ✓ 代码已更新"

# 1. 构建前端
echo "[1/4] 构建前端..."
cd "$SCRIPT_DIR/frontend"
pnpm build
echo "    ✓ 构建完成"

# 2. 部署前端到 Nginx
echo "[2/4] 部署前端..."
rm -rf /var/www/cma/assets/
cp -r dist/* /var/www/cma/
echo "    ✓ 部署完成"

# 3. 更新后端依赖
echo "[3/4] 更新后端..."
cd "$SCRIPT_DIR/backend"
source venv/bin/activate
pip install -r requirements.txt --quiet --no-cache-dir
deactivate
echo "    ✓ 依赖更新完成"

# 4. 重启后端服务
echo "[4/4] 重启后端服务..."
systemctl daemon-reload
systemctl restart cma-backend
systemctl reload nginx 2>/dev/null || nginx -s reload
echo "    ✓ 服务重启完成"

echo ""
echo "===== 部署完成 ====="
echo "    前端: https://cma.sxbh.ltd"
echo "    后端: http://127.0.0.1:8010/docs"
echo "    后端状态: systemctl status cma-backend"
