#!/bin/bash
# Auto-commit and push workspace to GitHub
# Runs every 12 hours via cron

WORKSPACE="/root/.openclaw/workspace"
LOG="/tmp/git-backup.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M UTC')
WEBHOOK="https://discord.com/api/webhooks/1475470748297592926/OMQvQBRyC6yvHsXEm7Y8WDyrI9kxJ_ph3IzgGcvkdcBetaW9zthdeaRQEdoPFiFJ28NY"

cd "$WORKSPACE" || exit 1

# Check if there's anything to commit
if git diff --quiet && git diff --cached --quiet && [ -z "$(git ls-files --others --exclude-standard)" ]; then
  echo "[$TIMESTAMP] Nothing to commit" >> "$LOG"
  exit 0
fi

# Stage and commit
git add -A
COMMIT_OUT=$(git commit -m "auto-backup: $TIMESTAMP" 2>&1)
echo "[$TIMESTAMP] $COMMIT_OUT" >> "$LOG"

# Push
if git push origin main >> "$LOG" 2>&1; then
  echo "[$TIMESTAMP] ✅ Push successful" >> "$LOG"
  curl -s -X POST "$WEBHOOK" \
    -H "Content-Type: application/json" \
    -d "{\"content\": \"🔄 **Git backup complete** — workspace pushed to GitHub\n\`$TIMESTAMP\`\"}" > /dev/null
else
  echo "[$TIMESTAMP] ❌ Push failed" >> "$LOG"
  curl -s -X POST "$WEBHOOK" \
    -H "Content-Type: application/json" \
    -d "{\"content\": \"⚠️ **Git backup FAILED** — push to GitHub failed\n\`$TIMESTAMP\`\"}" > /dev/null
fi
