#!/usr/bin/env bash

# Backup VM data script
# This script backs up Besu data from 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_DIR="${BACKUP_DIR:-/backup/vm}"
DATE=$(date +%Y%m%d-%H%M%S)


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

log_success "Backing up VM data: $VM_IP"

# Create backup directory
mkdir -p "$BACKUP_DIR"

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

# Backup data
log_warn "Backing up data..."
ssh besuadmin@$VM_IP "tar czf - /opt/besu/data /opt/besu/config" > "$BACKUP_DIR/vm-$VM_IP-$DATE.tar.gz"

if [ $? -eq 0 ]; then
    log_success "✓ Backup created: vm-$VM_IP-$DATE.tar.gz"
else
    log_error "✗ Backup 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 "Backup completed!"

