#!/bin/bash
# OpenClaw Memory Backup Script
# Runs daily to commit and push changes to the private backup repo.
#
# IMPORTANT DESIGN CHOICE
# - We never mutate the *live* workspace files for redaction.
# - Instead, we sync the workspace into a separate backup working tree,
#   redact there, then commit/push from that tree.

set -euo pipefail

SRC_DIR="/home/lagoon3/.openclaw/workspace"
BACKUP_DIR="/home/lagoon3/.openclaw/backup_repo"
REMOTE_URL="https://github.com/LLagoon3/openclaw-memory-backup.git"
BRANCH="master"

OPENCLAW_BIN="/home/lagoon3/.npm-global/bin/openclaw"
REDACTOR="$SRC_DIR/scripts/redact_backup_tree.py"

mkdir -p "$(dirname "$BACKUP_DIR")"

# 0) Ensure backup repo working tree exists
if [ ! -d "$BACKUP_DIR/.git" ]; then
  git clone "$REMOTE_URL" "$BACKUP_DIR"
fi

# 1) Update backup working tree
git -C "$BACKUP_DIR" fetch origin "$BRANCH" || true
git -C "$BACKUP_DIR" checkout "$BRANCH" >/dev/null 2>&1 || git -C "$BACKUP_DIR" checkout -b "$BRANCH"
# Prefer ff-only; fall back to hard reset to remote branch if needed.
if ! git -C "$BACKUP_DIR" pull --ff-only origin "$BRANCH"; then
  git -C "$BACKUP_DIR" reset --hard "origin/$BRANCH" || true
fi

# 2) Sync workspace contents into backup tree (excluding .git)
# --delete keeps the backup repo faithful to workspace state.
rsync -a --delete --exclude '.git' "$SRC_DIR/" "$BACKUP_DIR/"

# 3) Generate backup-only artifacts inside BACKUP_DIR
# 3.1) Copy external config (live file) into backup tree as openclaw_backup.json
cp /home/lagoon3/.openclaw/openclaw.json "$BACKUP_DIR/openclaw_backup.json"

# 3.2) Dump active cron jobs
"$OPENCLAW_BIN" cron list --json > "$BACKUP_DIR/active_crons.json"

# 3.3) Dump Python dependencies (for scripts)
# Avoid failing the whole backup if pip isn't available in PATH.
if command -v pip >/dev/null 2>&1; then
  pip freeze > "$BACKUP_DIR/requirements.txt" || true
fi

# 4) Redact secrets in the backup tree only
python3 "$REDACTOR" --root "$BACKUP_DIR" >/dev/null

# 5) Commit + push if changed
git -C "$BACKUP_DIR" add -A

if git -C "$BACKUP_DIR" diff-index --quiet HEAD --; then
  echo "[$(date)] No changes to backup."
else
  git -C "$BACKUP_DIR" commit -m "Auto-backup: $(date)" || true
  if git -C "$BACKUP_DIR" push origin "$BRANCH"; then
    echo "[$(date)] Backup successful."
  else
    echo "[$(date)] Backup failed to push."
    exit 1
  fi
fi
