#!/bin/bash
# Daily Brain Sync to Gitea
# Commits and pushes workspace state to ParzivalTD/Brain repo

WORKSPACE="/data/.openclaw/workspace"
LOG_FILE="/data/.openclaw/workspace/logs/brain-sync.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Ensure log directory exists
mkdir -p "$(dirname "$LOG_FILE")"

{
  echo "[$TIMESTAMP] Starting Brain sync..."
  
  cd "$WORKSPACE" || exit 1
  
  # Configure git if needed
  git config --global user.email "thelegion@stacklegion.dev" >/dev/null 2>&1
  git config --global user.name "ParzivalTD" >/dev/null 2>&1
  git config http.sslVerify false >/dev/null 2>&1
  
  # Check if remote exists, if not add it
  if ! git remote get-url brain >/dev/null 2>&1; then
    git remote add brain http://thelegion%40stacklegion.dev:RubiKa1IsHomeNoMore@168.231.66.248:32771/ParzivalTD/Brain.git
    echo "[$TIMESTAMP] Added 'brain' remote"
  fi
  
  # Stage changes
  git add -A
  
  # Check if there are changes to commit
  if ! git diff-index --quiet HEAD --; then
    # Commit changes
    git commit -m "Brain sync: $(date +'%Y-%m-%d %H:%M:%S')" >/dev/null 2>&1
    echo "[$TIMESTAMP] Committed changes"
  else
    echo "[$TIMESTAMP] No changes to commit"
  fi
  
  # Push to Gitea
  if git push -u brain master 2>&1; then
    echo "[$TIMESTAMP] ✅ Brain sync completed successfully"
  else
    echo "[$TIMESTAMP] ⚠️ Brain sync push failed (may retry on next sync)"
  fi
  
} >> "$LOG_FILE" 2>&1

exit 0
