#!/bin/bash
# 自动同步脚本

cd /root/.openclaw/workspace

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🔄 开始自动同步..."

# 1. 先尝试拉取远程更新（如果存在）
if git remote get-url origin >/dev/null 2>&1; then
    echo "    📡 检查远程更新..."
    git fetch origin
    
    # 检查是否有冲突
    LOCAL=$(git rev-parse @)
    REMOTE=$(git rev-parse @{u} 2>/dev/null || echo "")
    BASE=$(git merge-base @ @{u} 2>/dev/null || echo "")
    
    if [ -z "$REMOTE" ]; then
        echo "    ⚠️  首次推送，需要手动设置"
    elif [ "$LOCAL" = "$REMOTE" ]; then
        echo "    ✅ 本地与远程一致"
    elif [ "$LOCAL" = "$BASE" ]; then
        echo "    🔄 拉取远程更新..."
        git pull origin master
        echo "    ✅ 更新完成"
    elif [ "$REMOTE" = "$BASE" ]; then
        echo "    🚀 推送本地变更..."
        git push origin master
        echo "    ✅ 推送完成"
    else
        echo "    ⚠️  检测到冲突，需要手动处理"
        echo "    📝 请执行: cd /root/.openclaw/workspace && git status"
    fi
else
    echo "    ⚠️  未配置远程仓库"
    echo "    📝 请先配置: git remote add origin <url>"
fi

# 2. 如果有未提交的变更，自动提交
if ! git diff --quiet; then
    echo "    📝 提交本地变更..."
    git add .
    git commit -m "chore(auto-sync): 自动提交未保存的变更 $(date '+%Y-%m-%d %H:%M')"
    echo "    ✅ 本地变更已提交"
    
    # 如果有远程仓库，推送
    if git remote get-url origin >/dev/null 2>&1; then
        echo "    🚀 推送到远程..."
        git push origin master
    fi
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🎉 自动同步完成"