#!/bin/bash
# Workspace自动备份脚本，基于vala_git_workspace_backup.vala规范
WORKSPACE_DIR="/root/.openclaw/workspace-xiaobian"
cd "$WORKSPACE_DIR" || exit 1

# 配置远程仓库地址
git remote set-url origin https://ai_member_only:ai%40makee260301%23@git.valavala.com/ai_member_only/ai_member_xiaobian.git || true

# 拉取最新代码
git pull origin master || true
# 提交所有变更
git add .
git commit -m "auto backup $(date +'%Y-%m-%d %H:%M:%S')" || true
# 推送到远程仓库
git push origin master || true

mkdir -p "$WORKSPACE_DIR/logs"
# 备份成功后发送通知给李若松（基于user_id）
COMMIT_HASH=$(git rev-parse --short HEAD)
if [ $? -eq 0 ] || [ $? -eq 1 ]; then
  APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaobian/config.json)
  APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaobian/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')
  
  # 构造content JSON，避免转义问题
  CONTENT=$(printf '{"text":"✅ 小编Workspace每日自动备份完成（%s）\\n提交哈希：%s\\n所有Workspace变更已同步到远程Git仓库"}' "$(date +'%Y-%m-%d %H:%M')" "$COMMIT_HASH")
  
  # 使用jq生成正确的JSON格式，避免转义错误
  MESSAGE_TEXT="✅ 小编Workspace每日自动备份完成（$(date +'%Y-%m-%d %H:%M')）
提交哈希：$COMMIT_HASH
所有Workspace变更已同步到远程Git仓库"
  
  # 构造请求体
  REQUEST_BODY=$(jq -n \
    --arg rid "4aagb443" \
    --arg text "$MESSAGE_TEXT" \
    '{
      receive_id: $rid,
      msg_type: "text",
      content: "{\"text\":\($text | @json)}"
    }')
  
  # 发送请求
  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 "$REQUEST_BODY" >> "$WORKSPACE_DIR/logs/backup.log" 2>&1
fi

echo "✅ 备份完成：$(date)"
