#!/usr/bin/env bash

# Backup chaindata script for Besu nodes
# This script creates backups of chaindata volumes

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}"
RETENTION_DAYS="${RETENTION_DAYS:-30}"
DATE=$(date +%Y%m%d-%H%M%S)


log_success "Starting chaindata backup"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Backup validators
log_warn "Backing up validator chaindata..."
VALIDATOR_PODS=$(kubectl get pods -n "$NAMESPACE" -l component=validator -o jsonpath='{.items[*].metadata.name}')

for pod in $VALIDATOR_PODS; do
    log_warn "Backing up $pod..."
    
    # Create snapshot
    kubectl exec -n "$NAMESPACE" "$pod" -- tar czf - /data/besu > "$BACKUP_DIR/validator-$pod-$DATE.tar.gz"
    
    if [ $? -eq 0 ]; then
        log_success "✓ Backup created: validator-$pod-$DATE.tar.gz"
    else
        log_error "✗ Backup failed for $pod"
    fi
done

# Backup RPC nodes (optional - only if using full sync)
log_warn "Backing up RPC chaindata..."
RPC_PODS=$(kubectl get pods -n "$NAMESPACE" -l component=rpc -o jsonpath='{.items[*].metadata.name}')

for pod in $RPC_PODS; do
    log_warn "Backing up $pod..."
    
    # Create snapshot
    kubectl exec -n "$NAMESPACE" "$pod" -- tar czf - /data/besu > "$BACKUP_DIR/rpc-$pod-$DATE.tar.gz"
    
    if [ $? -eq 0 ]; then
        log_success "✓ Backup created: rpc-$pod-$DATE.tar.gz"
    else
        log_error "✗ Backup failed for $pod"
    fi
done

# Clean up old backups
log_warn "Cleaning up old backups (older than $RETENTION_DAYS days)..."
find "$BACKUP_DIR" -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete

log_success "Backup completed"

# Upload to Azure Blob Storage (optional)
if [ -n "$AZURE_STORAGE_ACCOUNT" ] && [ -n "$AZURE_STORAGE_CONTAINER" ]; then
    log_warn "Uploading backups to Azure Blob Storage..."
    
    # Install azure-cli if not present
    if ! command -v az &> /dev/null; then
        log_error "Azure CLI not found. Install it to upload backups."
        exit 1
    fi
    
    # Upload backups
    az storage blob upload-batch \
        --account-name "$AZURE_STORAGE_ACCOUNT" \
        --destination "$AZURE_STORAGE_CONTAINER" \
        --source "$BACKUP_DIR" \
        --pattern "*-$DATE.tar.gz"
    
    if [ $? -eq 0 ]; then
        log_success "✓ Backups uploaded to Azure Blob Storage"
    else
        log_error "✗ Upload failed"
    fi
fi

log_success "Backup process completed"

