#!/bin/bash
# sync-venv.sh — 将 git 仓库的最新代码同步到 agentsmeeting-venv 并重启
#
# 用法: bash deploy/linux/sync-venv.sh
# 位置: 在 246 上运行 (hmo@192.168.1.246)
#
# 原理: git 仓库 ~/projects/AgentsMeeting/ 是开发主阵地,
#       但 production dashboard 跑在 /home/hmo/agentsmeeting-venv/ 下。
#       这个脚本把仓库中的关键文件同步到 venv 并重启服务。

set -e

REPO_DIR="$HOME/projects/AgentsMeeting"
VENV_DIR="/home/hmo/agentsmeeting-venv"
DASH_LOG="/tmp/dash.log"

echo "=== sync-venv: $(date) ==="
echo "仓库: $REPO_DIR"
echo "目标: $VENV_DIR"

# 1. 确保仓库是最新
cd "$REPO_DIR"
git pull --rebase origin master 2>&1 | tail -2

# 2. 同步关键文件
echo "--- 同步文件 ---"
cp -v "$REPO_DIR/gateway/scripts/dashboard.py" "$VENV_DIR/dashboard.py"
cp -v "$REPO_DIR/gateway/scripts/service_registry.py" "$VENV_DIR/service_registry.py" 2>/dev/null || true
cp -v "$REPO_DIR/gateway/scripts/proc_guard.py" "$VENV_DIR/proc_guard.py" 2>/dev/null || true
cp -v "$REPO_DIR/gateway/scripts/tests_api.py" "$VENV_DIR/tests_api.py" 2>/dev/null || true
cp -v "$REPO_DIR/gateway/scripts/checklist_audit.py" "$VENV_DIR/checklist_audit.py" 2>/dev/null || true
cp -v "$REPO_DIR/gateway/scripts/templates/dashboard.html" "$VENV_DIR/templates/dashboard.html"

# 3. 重启 dashboard
echo "--- 重启 dashboard ---"
# 使用 fuser -k :5803 杀掉占端口的老进程（pkill 可能因进程命令行不含路径而漏杀）
if fuser -k 5803/tcp 2>/dev/null; then
    echo "杀掉旧 dashboard 进程 (fuser -k :5803)"
    sleep 2
fi

# 自动检测 repo 根目录并设为 AGENTSMEETING_ROOT（A-F 端点依赖此路径找 .git 和 gateway/temp）
export AGENTSMEETING_ROOT="$REPO_DIR"
# XMPP Bridge（EasyTier/RDP 操作通过 Windows 的 xmpp_bot :5802 代理）
export XMPP_BRIDGE_URL="http://192.168.1.16:5802"
cd "$VENV_DIR"
nohup python3 dashboard.py > "$DASH_LOG" 2>&1 &
sleep 3

# 4. 备份（用于回滚）
BACKUP_DIR="/tmp/sync-venv-backup-$(date +%s)"
mkdir -p "$BACKUP_DIR"
cp -v "$VENV_DIR/dashboard.py" "$BACKUP_DIR/" 2>/dev/null || true
cp -v "$VENV_DIR/tests_api.py" "$BACKUP_DIR/" 2>/dev/null || true
cp -v "$VENV_DIR/templates/dashboard.html" "$BACKUP_DIR/" 2>/dev/null || true
echo "备份: $BACKUP_DIR"

# 5. 验证 — K 测试无意外失败才算部署完成
echo "--- 部署后验证 ---"
if ! bash "$REPO_DIR/deploy/linux/post-deploy-check.sh"; then
    echo "!!! 验证失败，正在回滚 !!!"
    cp -v "$BACKUP_DIR/dashboard.py" "$VENV_DIR/dashboard.py" 2>/dev/null || true
    cp -v "$BACKUP_DIR/tests_api.py" "$VENV_DIR/tests_api.py" 2>/dev/null || true
    cp -v "$BACKUP_DIR/templates/dashboard.html" "$VENV_DIR/templates/dashboard.html" 2>/dev/null || true
    fuser -k 5803/tcp 2>/dev/null || true
    sleep 2
    cd "$VENV_DIR"
    nohup python3 dashboard.py > "$DASH_LOG" 2>&1 &
    sleep 3
    echo "回滚完成。验证日志："
    bash "$REPO_DIR/deploy/linux/post-deploy-check.sh" 2>&1 || true
    exit 1
fi

echo "=== sync-venv 完成: $(date) ==="
