#!/bin/bash
WORKSPACE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
cd "$WORKSPACE_DIR"
# 拉取最新代码
git pull origin main || true
# 提交所有变更
git add .
git commit -m "auto backup $(date +'%Y-%m-%d %H:%M:%S')" || true
# 推送到远程仓库
git push origin main
if [ $? -eq 0 ]; then
    echo "✅ 备份完成：$(date)"
    # 备份成功给李若松发送通知
    APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaokui/config.json)
    APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaokui/config.json)
    TOKEN=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" -H "Content-Type: application/json" -d "{\"app_id\":\"$APP_ID\",\"app_secret\":\"$APP_SECRET\"}" | jq -r '.tenant_access_token')
    curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"receive_id": "4aagb443", "msg_type": "text", "content": "{\"text\":\"✅ 工作区自动备份成功，已同步到公司Git仓库\"}"}' > /dev/null 2>&1
else
    echo "❌ 备份失败：$(date)"
    exit 1
fi
