#!/usr/bin/env bash

# Restore chaindata script for Besu nodes
# This script restores chaindata from backups

set -e

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

# Configuration
NAMESPACE="${NAMESPACE:-besu-network}"
BACKUP_DIR="${BACKUP_DIR:-/backup/chaindata}"
BACKUP_FILE="${1:-}"


if [ -z "$BACKUP_FILE" ]; then
    log_error "Error: Backup file not specified"
    echo "Usage: $0 <backup-file> [pod-name]"
    exit 1
fi

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

POD_NAME="${2:-}"

if [ -z "$POD_NAME" ]; then
    log_warn "Available pods:"
    kubectl get pods -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[*].metadata.name}'
    read -p "Enter pod name: " POD_NAME
fi

log_warn "Restoring chaindata to $POD_NAME from $BACKUP_FILE"
log_error "WARNING: This will overwrite existing chaindata. Continue? (y/N)"
read -r CONFIRM

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

# Scale down pod
log_warn "Scaling down pod..."
kubectl scale statefulset --replicas=0 -n "$NAMESPACE" $(kubectl get statefulset -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[0].metadata.name}')

# Wait for pod to terminate
log_warn "Waiting for pod to terminate..."
kubectl wait --for=delete pod/"$POD_NAME" -n "$NAMESPACE" --timeout=300s

# Restore data
log_warn "Restoring chaindata..."
cat "$BACKUP_FILE" | kubectl exec -i -n "$NAMESPACE" "$POD_NAME" -- tar xzf - -C /

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

# Scale up pod
log_warn "Scaling up pod..."
kubectl scale statefulset --replicas=1 -n "$NAMESPACE" $(kubectl get statefulset -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[0].metadata.name}')

# Wait for pod to be ready
log_warn "Waiting for pod to be ready..."
kubectl wait --for=condition=ready pod/"$POD_NAME" -n "$NAMESPACE" --timeout=300s

log_success "Restore completed"

