#!/bin/bash
# OpenClaw工作区自动备份脚本
AGENT_NAME="xiaoyan"
GIT_TOKEN="ef9dfa0b3ae3cfba010c1462b8f77e11a0d4289f"
GIT_USERNAME="xiaoyan-bot"
GIT_EMAIL="bot@valavala.com"
GIT_URL="https://git.valavala.com"
GIT_OWNER="vala_skillhub"
REPO_NAME="ai_member_${AGENT_NAME}"
REPO_URL="https://oauth2:${GIT_TOKEN}@${GIT_URL#https://}/${GIT_OWNER}/${REPO_NAME}.git"
WORK_DIR="/root/.openclaw/workspace-xiaoyan"
LOG_FILE="${WORK_DIR}/logs/git_backup.log"
mkdir -p "${WORK_DIR}/logs"

cd "$WORK_DIR" || exit 1

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

# 配置.gitignore排除敏感文件
cat > .gitignore <<EOF
secrets.md
.secrets
.env
*.key
*.pem
*.p12
credentials/
tmp/
logs/
*.log
.DS_Store
.vscode/
.idea/
EOF

# 检查是否已经初始化git
if [ ! -d .git ]; then
  git init >> "$LOG_FILE" 2>&1
  git config user.name "$GIT_USERNAME" >> "$LOG_FILE" 2>&1
  git config user.email "$GIT_EMAIL" >> "$LOG_FILE" 2>&1
  git remote add origin "$REPO_URL" >> "$LOG_FILE" 2>&1
fi

# 检查远程仓库是否存在，不存在则创建
http_code=$(curl -s -o /dev/null -w "%{http_code}" \
  "${GIT_URL}/api/v1/repos/${GIT_OWNER}/${REPO_NAME}" \
  -H "Authorization: token ${GIT_TOKEN}")

if [ "${http_code}" = "404" ]; then
  echo "远程仓库不存在，创建仓库${REPO_NAME}..." >> "$LOG_FILE"
  curl -s -X POST "${GIT_URL}/api/v1/orgs/${GIT_OWNER}/repos" \
    -H "Authorization: token ${GIT_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{"name": "'"${REPO_NAME}"'", "private": true, "description": "xiaoyan工作区自动备份", "auto_init": false}' >> "$LOG_FILE" 2>&1
fi

# 提交并推送
git add -A >> "$LOG_FILE" 2>&1
git commit -m "auto backup: $(date '+%Y-%m-%d %H:%M:%S')" >> "$LOG_FILE" 2>&1
git push -u origin main --force >> "$LOG_FILE" 2>&1

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