#!/bin/bash
set -e
# 从传入参数获取配置，无硬编码敏感信息
AGENT_NAME="$1"
GIT_TOKEN="$2"
GIT_USERNAME="$3"
GIT_EMAIL="$4"
GIT_REPO_URL="${5:-https://git.valavala.com/${GIT_USERNAME}/ai_member_${AGENT_NAME}.git}"
CRON_SCHEDULE="${6:-30 8 * * *}"
# 自动创建Git仓库（如果不存在）
REPO_NAME="ai_member_${AGENT_NAME}"
echo "🔍 检查Git仓库是否存在: $REPO_NAME"
REPO_CHECK=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token $GIT_TOKEN" "https://git.valavala.com/api/v1/repos/$GIT_USERNAME/$REPO_NAME")
if [ "$REPO_CHECK" -eq 404 ]; then
  echo "🆕 仓库不存在，自动创建中..."
  CREATE_RESPONSE=$(curl -s -X POST "https://git.valavala.com/api/v1/user/repos" \
    -H "Authorization: token $GIT_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
          \"name\": \"$REPO_NAME\",
          \"private\": false,
          \"description\": \"${AGENT_NAME} workspace 备份\",
          \"auto_init\": false
        }")
  if echo "$CREATE_RESPONSE" | grep -q '"id":'; then
    echo "✅ 仓库创建成功: https://git.valavala.com/$GIT_USERNAME/$REPO_NAME"
  else
    echo "❌ 仓库创建失败: $CREATE_RESPONSE"
    exit 1
  fi
elif [ "$REPO_CHECK" -eq 200 ]; then
  echo "✅ 仓库已存在，跳过创建"
else
  echo "⚠️  仓库检查失败，HTTP状态码: $REPO_CHECK，继续执行配置"
fi
WORKSPACE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../" && pwd)"
# 初始化Git仓库
cd "$WORKSPACE_DIR"
if [ ! -d .git ]; then
  git init
fi
# 配置敏感文件过滤规则
cat > .gitignore <<EOF
secrets.md
.secrets
*.env
*.pem
*.key
*.crt
.DS_Store
node_modules/
logs/
tmp/
temp/
*.log
EOF
# 配置Git用户信息
git config user.name "$GIT_USERNAME"
git config user.email "$GIT_EMAIL"
# 配置远程仓库地址（动态拼接Token）
FULL_REPO_URL=$(echo "$GIT_REPO_URL" | sed "s|https://|https://$GIT_USERNAME:$GIT_TOKEN@|")
git remote remove origin 2>/dev/null || true
git remote add origin "$FULL_REPO_URL"
# 首次提交推送
git add .
git commit -m "initial backup $(date +'%Y-%m-%d %H:%M:%S')" || true
git branch -M main
git push -u origin main || true
# 创建日志目录
mkdir -p "$WORKSPACE_DIR/logs"
# 配置定时任务，避免重复添加
BACKUP_SCRIPT_PATH="$WORKSPACE_DIR/skills/vala_git_workspace_backup/scripts/backup.sh"
chmod +x "$BACKUP_SCRIPT_PATH"
(crontab -l 2>/dev/null | grep -v "$BACKUP_SCRIPT_PATH"; echo "$CRON_SCHEDULE $BACKUP_SCRIPT_PATH >> $WORKSPACE_DIR/logs/git_backup.log 2>&1") | crontab -
echo "✅ 配置完成，定时备份任务已设置：$CRON_SCHEDULE"
