#!/bin/bash
# Config Guard - Backs up openclaw.json before any configure/config commands
# Install: source this in .zshrc or run directly to create a backup

CONFIG_FILE="$HOME/.openclaw/openclaw.json"
BACKUP_DIR="$HOME/.openclaw/config-backups"

backup_config() {
    mkdir -p "$BACKUP_DIR"
    local timestamp=$(date +%Y%m%d-%H%M%S)
    local backup="$BACKUP_DIR/openclaw-$timestamp.json"
    cp "$CONFIG_FILE" "$backup"
    echo "✅ Config backed up to: $backup"
}

restore_latest() {
    local latest=$(ls -t "$BACKUP_DIR"/openclaw-*.json 2>/dev/null | head -1)
    if [ -z "$latest" ]; then
        echo "❌ No backups found"
        return 1
    fi
    echo "Restoring from: $latest"
    cp "$latest" "$CONFIG_FILE"
    echo "✅ Config restored. Restart gateway: openclaw gateway restart"
}

list_backups() {
    echo "📋 Config backups:"
    ls -lht "$BACKUP_DIR"/openclaw-*.json 2>/dev/null || echo "  No backups found"
}

diff_with_latest() {
    local latest=$(ls -t "$BACKUP_DIR"/openclaw-*.json 2>/dev/null | head -1)
    if [ -z "$latest" ]; then
        echo "❌ No backups to compare"
        return 1
    fi
    echo "Comparing current config with: $latest"
    diff <(python3 -m json.tool "$latest") <(python3 -m json.tool "$CONFIG_FILE") || echo "(no differences)"
}

# Run directly: backup_config, restore, list, diff
case "${1:-backup}" in
    backup)  backup_config ;;
    restore) restore_latest ;;
    list)    list_backups ;;
    diff)    diff_with_latest ;;
    *)       echo "Usage: config-guard.sh [backup|restore|list|diff]" ;;
esac
