#!/usr/bin/env bash

# Restore VM data script
# This script restores Besu data to a VM

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Configuration
VM_IP="${1:-}"
BACKUP_FILE="${2:-}"


if [ -z "$VM_IP" ] || [ -z "$BACKUP_FILE" ]; then
    log_error "Error: VM IP or backup file not provided"
    echo "Usage: $0 <vm-ip> <backup-file>"
    exit 1
fi

if [ ! -f "$BACKUP_FILE" ]; then
    log_error "Error: Backup file not found: $BACKUP_FILE"
    exit 1
fi

log_success "Restoring VM data: $VM_IP from $BACKUP_FILE"
log_error "WARNING: This will overwrite existing data. Continue? (y/N)"
read -r CONFIRM

if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
    echo "Restore cancelled"
    exit 0
fi

# Stop Besu container
log_warn "Stopping Besu container..."
ssh besuadmin@$VM_IP "docker compose -f /opt/besu/docker-compose.yml down"

# Restore data
log_warn "Restoring data..."
cat "$BACKUP_FILE" | ssh besuadmin@$VM_IP "sudo tar xzf - -C /"

if [ $? -eq 0 ]; then
    log_success "✓ Data restored"
else
    log_error "✗ Restore failed"
    exit 1
fi

# Restart Besu container
log_warn "Restarting Besu container..."
ssh besuadmin@$VM_IP "docker compose -f /opt/besu/docker-compose.yml up -d"

log_success "Restore completed!"

