#!/usr/bin/env bash

# Deploy Besu network on VMs/VMSS across multiple regions
# This script orchestrates VM deployment using Terraform

set -e

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

# Configuration
REGIONS=("eastus" "westus" "westeurope")
VALIDATOR_COUNT=2
SENTRY_COUNT=2
RPC_COUNT=2
USE_VMSS=false


log_success "Deploying Besu network on VMs..."

# Check prerequisites
if ! command -v terraform &> /dev/null; then
    log_error "Error: Terraform not found. Please install Terraform."
    exit 1
fi

if ! command -v az &> /dev/null; then
    log_error "Error: Azure CLI not found. Please install Azure CLI."
    exit 1
fi

# Check if logged in to Azure
if ! az account show &> /dev/null; then
    log_error "Error: Not logged in to Azure. Please run 'az login'."
    exit 1
fi

# Check for SSH public key
if [ -z "$SSH_PUBLIC_KEY" ]; then
    if [ -f ~/.ssh/id_rsa.pub ]; then
        SSH_PUBLIC_KEY=$(cat ~/.ssh/id_rsa.pub)
        log_warn "Using SSH key from ~/.ssh/id_rsa.pub"
    else
        log_error "Error: SSH public key not found. Set SSH_PUBLIC_KEY environment variable or create ~/.ssh/id_rsa.pub"
        exit 1
    fi
fi

# Initialize Terraform
log_warn "Initializing Terraform..."
cd "$PROJECT_ROOT/terraform"
terraform init

# Create terraform.tfvars for VM deployment
cat > terraform.tfvars.vm <<EOF
vm_deployment_enabled = true
vm_regions = ${REGIONS[@]}
validator_vm_count = $VALIDATOR_COUNT
sentry_vm_count = $SENTRY_COUNT
rpc_vm_count = $RPC_COUNT
use_vmss = $USE_VMSS
ssh_public_key = "$SSH_PUBLIC_KEY"
vm_size_validator = "Standard_D4s_v3"
vm_size_sentry = "Standard_D4s_v3"
vm_size_rpc = "Standard_D8s_v3"
EOF

# Plan deployment
log_warn "Planning Terraform deployment..."
terraform plan -var-file=terraform.tfvars.vm -out=vm-deployment.tfplan

# Apply deployment
log_warn "Applying Terraform deployment..."
read -p "Do you want to proceed with VM deployment? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    terraform apply vm-deployment.tfplan
    log_success "✓ VM deployment completed"
else
    log_warn "Deployment cancelled"
    exit 0
fi

# Get VM information
log_warn "Getting VM information..."
terraform output -json > vm-deployment-output.json

log_success "VM deployment completed successfully!"
log_warn "VM information saved to terraform/vm-deployment-output.json"

# Display VM information
log_warn "VM Information:"
jq -r '.vm_names.value[]' terraform/vm-deployment-output.json 2>/dev/null || echo "VM information not available"

log_success "Deployment complete!"

