#!/bin/bash
# Upload Genesis File to Azure Storage and Deploy to All Besu Nodes
# This script uploads the genesis file to Azure Storage and downloads it to all VMs

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE1_DIR="$SCRIPT_DIR/../"
GENESIS_FILE="$PHASE1_DIR/config/genesis-138.json"

if [ ! -f "$GENESIS_FILE" ]; then
    echo "Error: Genesis file not found: $GENESIS_FILE"
    exit 1
fi

echo "=========================================="
echo "Upload Genesis File to Azure Storage"
echo "and Deploy to All Besu Nodes"
echo "=========================================="
echo ""

# Get storage account from Terraform output
cd "$PHASE1_DIR"
# Try to get backup storage account from first region, fallback to boot diagnostics
STORAGE_ACCOUNT=$(terraform output -json 2>/dev/null | jq -r '.storage_accounts.value.backups | to_entries[0].value.backup_storage // empty' || echo "")

if [ -z "$STORAGE_ACCOUNT" ]; then
    # Fallback to boot diagnostics storage
    STORAGE_ACCOUNT=$(terraform output -json 2>/dev/null | jq -r '.storage_accounts.value.boot_diagnostics | to_entries[0].value.name // empty' || echo "")
fi

if [ -z "$STORAGE_ACCOUNT" ]; then
    echo "Error: Could not retrieve storage account from Terraform output"
    echo "Please ensure Terraform has been applied and outputs are available"
    exit 1
fi

echo "Storage Account: $STORAGE_ACCOUNT"
echo "Genesis File: $GENESIS_FILE"
echo ""

# Get storage account key
echo "Getting storage account key..."
STORAGE_KEY=$(az storage account keys list \
    --account-name "$STORAGE_ACCOUNT" \
    --resource-group az-p-cus-rg-comp-001 \
    --query "[0].value" \
    --output tsv 2>/dev/null || echo "")

if [ -z "$STORAGE_KEY" ]; then
    echo "Error: Could not retrieve storage account key"
    echo "Please ensure you have permissions to list storage account keys"
    exit 1
fi

# Create container if it doesn't exist
echo "Creating container 'genesis' if it doesn't exist..."
az storage container create \
    --name genesis \
    --account-name "$STORAGE_ACCOUNT" \
    --account-key "$STORAGE_KEY" \
    --public-access off \
    --output none 2>/dev/null || echo "Container may already exist"

# Upload genesis file
echo "Uploading genesis file..."
az storage blob upload \
    --account-name "$STORAGE_ACCOUNT" \
    --account-key "$STORAGE_KEY" \
    --container-name genesis \
    --name genesis-138.json \
    --file "$GENESIS_FILE" \
    --overwrite

echo ""
echo "=========================================="
echo "Upload Complete! Deploying to VMs..."
echo "=========================================="
echo ""

# Get all region configurations
REGIONS=("cus" "eus" "eus2" "wus" "wus2")
REGION_NAMES=("centralus" "eastus" "eastus2" "westus" "westus2")

# Generate SAS token for download
echo "Generating SAS token..."
SAS_TOKEN=$(az storage container generate-sas \
    --name genesis \
    --account-name "$STORAGE_ACCOUNT" \
    --account-key "$STORAGE_KEY" \
    --permissions r \
    --expiry $(date -u -d "+1 hour" +%Y-%m-%dT%H:%MZ) \
    --output tsv 2>/dev/null || echo "")

if [ -z "$SAS_TOKEN" ]; then
    echo "Error: Could not generate SAS token. Cannot download to VMs."
    echo "Please ensure you have permissions to generate SAS tokens."
    exit 1
fi

BLOB_URL="https://${STORAGE_ACCOUNT}.blob.core.windows.net/genesis/genesis-138.json"
DOWNLOAD_URL="${BLOB_URL}?${SAS_TOKEN}"

echo "Download URL generated (valid for 1 hour)"
echo ""

# Deploy to all VMs
SUCCESS_COUNT=0
FAILED_REGIONS=()

for i in "${!REGIONS[@]}"; do
    REGION="${REGIONS[$i]}"
    REGION_NAME="${REGION_NAMES[$i]}"
    RG="az-p-${REGION}-rg-comp-001"
    
    echo "----------------------------------------"
    echo "Deploying to ${REGION_NAME} (${REGION})..."
    echo "----------------------------------------"
    
    # Get VM name
    VM=$(az vm list --resource-group "$RG" --query "[0].name" -o tsv 2>/dev/null || echo "")
    
    if [ -z "$VM" ]; then
        echo "  ⚠️  VM not found in resource group: $RG"
        FAILED_REGIONS+=("$REGION")
        continue
    fi
    
    echo "  VM: $VM"
    
    # Download genesis file to VM
    echo "  Downloading genesis file..."
    
    # Create script file and execute it
    SCRIPT_CONTENT="curl -s -f '${DOWNLOAD_URL}' -o /tmp/genesis-138.json
if [ \$? -eq 0 ] && [ -f /tmp/genesis-138.json ]; then
  FILE_SIZE=\$(wc -c < /tmp/genesis-138.json)
  if [ \$FILE_SIZE -gt 1000 ]; then
    sudo mv /tmp/genesis-138.json /opt/besu/config/genesis.json
    sudo chmod 644 /opt/besu/config/genesis.json
    sudo chown besuadmin:besuadmin /opt/besu/config/genesis.json
    echo SUCCESS: Genesis file installed \$FILE_SIZE bytes
    ls -lh /opt/besu/config/genesis.json
  else
    echo ERROR: File too small \$FILE_SIZE bytes
    exit 1
  fi
else
  echo ERROR: Download failed
  exit 1
fi"
    
    # Base64 encode the script to avoid escaping issues
    ENCODED_SCRIPT=$(echo "$SCRIPT_CONTENT" | base64 -w 0)
    
    RESULT=$(az vm run-command invoke \
        --resource-group "$RG" \
        --name "$VM" \
        --command-id RunShellScript \
        --scripts "echo '${ENCODED_SCRIPT}' | base64 -d | bash" \
        2>&1 | grep -E '(stdout|SUCCESS|ERROR|bytes|genesis|config)' | head -10 || echo "ERROR")
    
    if echo "$RESULT" | grep -q "SUCCESS"; then
        echo "  ✅ Genesis file downloaded successfully"
        
        # Restart Besu container
        echo "  Restarting Besu container..."
        az vm run-command invoke \
            --resource-group "$RG" \
            --name "$VM" \
            --command-id RunShellScript \
            --scripts "cd /opt/besu && sudo docker compose restart besu" \
            --output none 2>&1 | grep -v "Enable succeeded" || true
        
        echo "  ✅ Besu container restarted"
        ((SUCCESS_COUNT++))
    else
        echo "  ❌ Failed to download genesis file"
        echo "  Result: $RESULT"
        FAILED_REGIONS+=("$REGION")
    fi
    
    echo ""
done

echo "=========================================="
echo "Deployment Summary"
echo "=========================================="
echo "Successfully deployed: $SUCCESS_COUNT/${#REGIONS[@]} regions"
echo ""

if [ ${#FAILED_REGIONS[@]} -gt 0 ]; then
    echo "Failed regions:"
    for REGION in "${FAILED_REGIONS[@]}"; do
        echo "  - $REGION"
    done
    echo ""
fi

if [ $SUCCESS_COUNT -eq ${#REGIONS[@]} ]; then
    echo "✅ All genesis files deployed successfully!"
    echo ""
    echo "Waiting 30 seconds for Besu containers to start..."
    sleep 30
    echo ""
    echo "You can now test RPC endpoints:"
    echo "  curl -X POST https://rpc.d-bis.org \\"
    echo "    -H 'Content-Type: application/json' \\"
    echo "    --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_chainId\",\"params\":[],\"id\":1}'"
    echo ""
else
    echo "⚠️  Some deployments failed. Please check the errors above."
    exit 1
fi

