#!/bin/bash
set -e

# 配置信息
AGENT_NAME="xiaoban"
WORK_DIR="/root/.openclaw/workspace-xiaoban"
LOG_FILE="${WORK_DIR}/logs/backup.log"
mkdir -p "${WORK_DIR}/logs"

# 进入workspace目录
cd "$WORK_DIR" || exit 1

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 开始备份工作区..." >> "$LOG_FILE"

# 配置git信息
git config user.name "xiaoban"
git config user.email "xiaoban@valavala.com"

# 添加所有文件，自动排除.gitignore里的内容（包括secrets.md）
git add .

# 提交变更
COMMIT_MSG="自动备份 $(date +'%Y-%m-%d %H:%M:%S')"
git commit -m "$COMMIT_MSG" || echo "无变更需要提交" >> "$LOG_FILE" 2>&1

# 推送到远程仓库
git push https://git.valavala.com/ai_member_only/ai_member_xiaoban master >> "$LOG_FILE" 2>&1

if [ $? -eq 0 ]; then
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] 工作区备份成功：$COMMIT_MSG" >> "$LOG_FILE"
  # 备份成功给李若松发消息（基于user_id）
  APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaoban/config.json)
  APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaoban/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\":\"✅ xiaoban工作区自动备份成功，仓库地址：https://git.valavala.com/ai_member_only/ai_member_xiaoban\"}"
    }' > /dev/null 2>&1
  exit 0
else
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] 工作区备份失败，请检查日志：${LOG_FILE}" >> "$LOG_FILE"
  # 备份失败通知
  APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaoban/config.json)
  APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaoban/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\":\"❌ xiaoban工作区自动备份失败，请检查日志：/root/.openclaw/workspace-xiaoban/logs/backup.log\"}"
    }' > /dev/null 2>&1
  exit 1
fi