#!/bin/bash

# ============================================
# 增量同步代码到 NAS 并重新部署
# 当修复 bug 后，运行这个脚本自动同步并重新部署
# ============================================

set -e

# 配置信息
NAS_IP="192.168.2.154"
NAS_USER="admin"
LOCAL_PROJECT="/Users/chufeng/.openclaw/sanguo_projects/sanguo_quant_live"
NAS_TARGET="/volume1/stock/sanguo_vnpy"

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo "============================================"
echo "  增量同步 + 自动重新部署"
echo "============================================"
echo ""

# 拉取最新代码
log_info "1/4: 拉取最新代码"
cd "$LOCAL_PROJECT"
git pull origin main
log_info "✅ 代码已更新"
echo ""

# 增量同步到 NAS
log_info "2/4: 增量同步到 NAS"
# 同步整个项目，包括策略和框架代码
# 任何文件修改（包括 vnpy 框架代码）都会同步到 NAS
rsync -av --delete \
    "$LOCAL_PROJECT"/ \
    "$NAS_USER@$NAS_IP:$NAS_TARGET"/ \
    --exclude='.git' \
    --exclude='__pycache__' \
    --exclude='*.log' \
    --exclude='*.pyc' \
    --exclude='.ipynb_checkpoints' \
    --exclude='backtest_results/*.png' \
    --exclude='.DS_Store'

log_info "✅ 同步完成"
echo ""

# 重启 Docker 容器
log_info "3/4: 重启 Docker 容器"
ssh "$NAS_USER@$NAS_IP" << 'EOF'
cd /volume1/stock/sanguo_vnpy

# 添加 docker 到 PATH
export PATH=$PATH:/var/packages/Docker/target/usr/bin

# 停止旧容器
if docker ps -q -f name=sanguo_vnpy | grep -q .; then
    docker stop sanguo_vnpy
fi

# 重新构建启动
/var/packages/Docker/target/usr/bin/docker-compose up -d --build

# 等待启动
sleep 10

# 检查状态
if docker ps -q -f name=sanguo_vnpy | grep -q .; then
    echo "✅ 容器重启成功"
else
    echo "❌ 容器启动失败"
    exit 1
fi
EOF

log_info "✅ 容器重启完成"
echo ""

# 运行回测
log_info "4/4: 启动自动化回测"
ssh "$NAS_USER@$NAS_IP" "cd /volume1/stock/sanguo_vnpy/scripts && ./run_backtest_auto.sh"

echo ""
log_info "🎉 完成！代码已同步，容器已重启，回测已启动！"
echo ""
