#!/bin/bash
# 任务名称：工作区Git备份
# 执行时间：每天 08:00
# 归属 Agent：xiaoxi
# 通知对象：李若松（user_id: 4aagb443）

set -e

export PATH=/root/.nvm/versions/node/v24.14.0/bin:$PATH
LOG_FILE="/var/log/xiaoxi_daily_backup.log"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# 获取飞书token
get_token() {
    local APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaoxi/config.json)
    local APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaoxi/config.json)
    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'
}

# 发送文本消息给个人（user_id）
send_msg() {
    local TOKEN=$1
    local USER_ID=$2
    local TEXT=$3
    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\":\"$USER_ID\",\"msg_type\":\"text\",\"content\":\"{\\\"text\\\":\\\"$TEXT\\\"}\"}" > /dev/null 2>&1
}

log "开始执行工作区备份"

# 进入工作区目录
cd /root/.openclaw/workspace

# 确保敏感文件不会被提交到Git
if ! grep -q "secrets.md" .gitignore 2>/dev/null; then
    echo "secrets.md" >> .gitignore
    echo "*.env" >> .gitignore
    echo "memory/*.private.md" >> .gitignore
fi

# 提交所有变更
git add .
git commit -m "🤖 每日自动备份 - $(date +'%Y-%m-%d %H:%M:%S')" || { log "没有新的变更需要提交"; }

# 推送到远程仓库
TOKEN=$(get_token)
if git push; then
    log "Git推送成功"
    send_msg "$TOKEN" "4aagb443" "✅ 小溪工作区每日备份成功，备份时间：$(date +'%Y-%m-%d %H:%M:%S')"
else
    log "Git推送失败"
    send_msg "$TOKEN" "4aagb443" "❌ 小溪工作区每日备份失败！请检查Git仓库配置和网络连接，错误时间：$(date +'%Y-%m-%d %H:%M:%S')"
    exit 1
fi

log "备份任务完成"
