#!/bin/bash

# 自动双向同步脚本
# 每分钟运行一次，双向同步本地和远程Gitee
# 错误处理：失败了记录日志不继续错误扩散

PROJECT_DIR="/Users/chufeng/.openclaw/sanguo_projects/sanguo_quant_live"
LOG_FILE="$PROJECT_DIR/auto-sync.log"
MAX_RETRIES=2

# 确保目录存在
cd "$PROJECT_DIR" || {
    echo "[$(date)] ERROR: Failed to cd into $PROJECT_DIR" >> "$LOG_FILE"
    exit 1
}

echo "[$(date)] Starting auto sync..." >> "$LOG_FILE"

# 第一步：git pull 拉取远程变更
echo "[$(date)] Step 1: git pull origin main" >> "$LOG_FILE"
git pull origin main
exit_code=$?

if [ $exit_code -ne 0 ]; then
    echo "[$(date)] WARNING: git pull failed with exit code $exit_code" >> "$LOG_FILE"
    # pull失败不推送，避免冲突
    exit 1
fi

echo "[$(date)] git pull success" >> "$LOG_FILE"

# 第二步：添加所有变更（包括未跟踪文件）
echo "[$(date)] Step 2: Adding all changes..." >> "$LOG_FILE"
git add .
exit_code=$?
if [ $exit_code -ne 0 ]; then
    echo "[$(date)] ERROR: git add failed with exit code $exit_code" >> "$LOG_FILE"
    exit 1
fi

# 第三步：检查是否有内容需要提交
if git diff --cached --quiet; then
    # 没有变更需要提交，正常退出
    echo "[$(date)] No changes to commit, exiting." >> "$LOG_FILE"
    exit 0
fi

# 有变更，进行提交
echo "[$(date)] Step 3: Found changes to commit, committing..." >> "$LOG_FILE"

git commit -m "auto-sync: $(date '+%Y-%m-%d %H:%M:%S')"
exit_code=$?
if [ $exit_code -ne 0 ]; then
    echo "[$(date)] ERROR: git commit failed with exit code $exit_code" >> "$LOG_FILE"
    exit 1
fi

# 推送到远程
echo "[$(date)] Step 3: Pushing to origin/main..." >> "$LOG_FILE"

for i in $(seq 1 $MAX_RETRIES); do
    git push origin main
    exit_code=$?
    if [ $exit_code -eq 0 ]; then
        echo "[$(date)] Push success! Sync complete." >> "$LOG_FILE"
        exit 0
    fi
    echo "[$(date)] Push attempt $i failed, retrying..." >> "$LOG_FILE"
    sleep 2
done

echo "[$(date)] ERROR: Push failed after $MAX_RETRIES attempts" >> "$LOG_FILE"
exit 1
