#!/usr/bin/env bash
# Empty Besu data directories and restart with new genesis.json
# Run from Nginx proxy to connect to all Besu nodes

set -e

NGINX_IP="${NGINX_PROXY_IP:-20.160.58.99}"
GENESIS_FILE="${GENESIS_FILE:-/tmp/genesis.json}"

# Define node IPs (update these with actual IPs from Azure)
# Format: "region_name:ip_address"
NODES=(
    "cus:10.0.1.4"      # Central US - Update with actual IP
    "eus:10.0.2.4"      # East US - Update with actual IP
    "eus2:10.0.3.4"     # East US 2 - Update with actual IP
    "wus:10.0.4.4"      # West US - Update with actual IP
    "wus2:10.0.5.4"     # West US 2 - Update with actual IP
)

# Besu data directory path
BESU_DATA_DIR="/opt/besu/data"
COMPOSE_DIR="/opt/docker-compose"
COMPOSE_FILE="docker-compose.yml"

# Function to empty data directory on a node
empty_and_restart_node() {
    local node_name=$1
    local node_ip=$2
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "📋 Processing $node_name ($node_ip)"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 besuadmin@"$node_ip" <<EOF
        set -e
        
        echo "  ✅ Connected to $node_name"
        
        # Stop Besu container
        echo "  🔄 Stopping Besu container..."
        if [ -f "$COMPOSE_DIR/$COMPOSE_FILE" ]; then
            cd "$COMPOSE_DIR"
            sudo docker-compose -f "$COMPOSE_FILE" down besu 2>/dev/null || true
            sleep 2
        else
            echo "  ⚠️  Docker compose file not found at $COMPOSE_DIR/$COMPOSE_FILE"
        fi
        
        # Empty data directory
        echo "  🗑️  Emptying data directory..."
        if [ -d "$BESU_DATA_DIR" ]; then
            sudo rm -rf "$BESU_DATA_DIR"/* "$BESU_DATA_DIR"/.[^.]* 2>/dev/null || true
            sudo mkdir -p "$BESU_DATA_DIR" 2>/dev/null || true
            sudo chown -R besuadmin:besuadmin "$BESU_DATA_DIR" 2>/dev/null || true
            echo "  ✅ Data directory emptied: $BESU_DATA_DIR"
        else
            echo "  ⚠️  Data directory not found: $BESU_DATA_DIR"
            sudo mkdir -p "$BESU_DATA_DIR"
            sudo chown -R besuadmin:besuadmin "$BESU_DATA_DIR"
        fi
        
        # Copy new genesis.json
        echo "  📤 Copying new genesis.json..."
        if [ -f "$GENESIS_FILE" ]; then
            sudo cp "$GENESIS_FILE" /opt/besu/config/genesis.json
            sudo chown besuadmin:besuadmin /opt/besu/config/genesis.json
            echo "  ✅ Genesis.json updated"
        else
            echo "  ⚠️  Genesis file not found at $GENESIS_FILE"
            echo "     Creating symlink..."
            sudo ln -sf "$GENESIS_FILE" /opt/besu/config/genesis.json 2>/dev/null || true
        fi
        
        # Restart Besu container
        echo "  🔄 Restarting Besu container..."
        if [ -f "$COMPOSE_DIR/$COMPOSE_FILE" ]; then
            cd "$COMPOSE_DIR"
            sudo docker-compose -f "$COMPOSE_FILE" up -d besu
            echo "  ✅ Besu container restarted"
        else
            echo "  ⚠️  Cannot restart - compose file not found"
        fi
        
        echo "  ✅ $node_name processing complete"
EOF
    
    if [ $? -eq 0 ]; then
        echo "✅ $node_name: Success"
    else
        echo "❌ $node_name: Failed"
        return 1
    fi
    echo ""
}

# Main execution
main() {
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Empty Besu Data Directories and Restart with New Genesis"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    echo "Nginx Proxy: $NGINX_IP"
    echo "Genesis File: $GENESIS_FILE"
    echo "Nodes to process: ${#NODES[@]}"
    echo ""
    
    # First, copy genesis.json to Nginx proxy if not already there
    if [ ! -f "$GENESIS_FILE" ]; then
        echo "⚠️  Genesis file not found at $GENESIS_FILE"
        echo "   Please copy genesis.json to $GENESIS_FILE first"
        exit 1
    fi
    
    # Process each node
    FAILED_NODES=()
    for node_entry in "${NODES[@]}"; do
        IFS=':' read -r node_name node_ip <<< "$node_entry"
        
        if empty_and_restart_node "$node_name" "$node_ip"; then
            echo "✅ $node_name completed successfully"
        else
            echo "❌ $node_name failed"
            FAILED_NODES+=("$node_name")
        fi
        echo ""
    done
    
    # Summary
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Summary"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    if [ ${#FAILED_NODES[@]} -eq 0 ]; then
        echo "✅ All nodes processed successfully!"
    else
        echo "⚠️  Some nodes failed:"
        for node in "${FAILED_NODES[@]}"; do
            echo "   • $node"
        done
        exit 1
    fi
    echo ""
}

# Run main function
main "$@"

