#!/bin/bash
# OpenClaw Backup to Gitea
# Backs up workspace + state directory to Gitea repo

set -e

BACKUP_DIR="$HOME/.openclaw/workspace"
STATE_DIR="$HOME/.openclaw"
REPO_DIR="$HOME/openclaw-backup"
# Use SSH URL (requires SSH key setup) or HTTP with credentials
# SSH: git@gitea.kangaroo-eel.ts.net:Anthony/openclaw-backup.git
# HTTP with token: http://username:token@gitea.kangaroo-eel.ts.net:3000/Anthony/openclaw-backup.git
REPO_URL="${GITEA_BACKUP_URL:-git@gitea.kangaroo-eel.ts.net:Anthony/openclaw-backup.git}"
LOG_FILE="$HOME/.openclaw/workspace/logs/backup.log"

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

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

log "Starting backup..."

# Clone or update repo
if [ -d "$REPO_DIR" ]; then
    log "Updating existing repo..."
    cd "$REPO_DIR"
    git pull --rebase || log "Warning: pull failed, continuing..."
else
    log "Cloning backup repo..."
    git clone "$REPO_URL" "$REPO_DIR"
    cd "$REPO_DIR"
fi

# Backup workspace (excluding scripts directory to avoid recursion)
log "Backing up workspace..."
rsync -av --delete \
    --exclude='.git' \
    --exclude='node_modules' \
    --exclude='*.log' \
    "$BACKUP_DIR/" "$REPO_DIR/workspace/"

# Backup state directory (critical config)
log "Backing up state directory..."
mkdir -p "$REPO_DIR/state"
rsync -av --delete \
    --include='openclaw.json' \
    --include='cron/' \
    --include='cron/**' \
    --include='skills/' \
    --include='skills/**' \
    --include='devices/' \
    --include='devices/**' \
    --exclude='*' \
    "$STATE_DIR/" "$REPO_DIR/state/"

# Commit and push
log "Committing changes..."
cd "$REPO_DIR"
git add -A
git diff --cached --quiet || git commit -m "Backup: $(date '+%Y-%m-%d %H:%M:%S')"
git push origin main || git push origin master

log "Backup complete!"
