#!/bin/bash
# Backend VM Setup Script
# Prepares scripts for backend VM configuration

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHASE1_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=========================================="
echo "Backend VM Setup Preparation"
echo "=========================================="
echo ""

cd "$PHASE1_DIR"

# Get backend VM details
BACKEND_VMS=$(terraform output -json 2>/dev/null | jq -r '.phase1_us_regions.value | to_entries[] | "\(.key):\(.value.private_ips[0]):\(.value.vm_names[0])"' || echo "")

if [ -z "$BACKEND_VMS" ]; then
    echo "Error: Backend VMs not found"
    exit 1
fi

echo "Backend VMs require VPN/Bastion access for SSH."
echo "Preparing setup scripts for each VM..."
echo ""

# Create setup package for each VM
while IFS=: read -r region ip vm_name; do
    if [ -n "$ip" ] && [ "$ip" != "null" ]; then
        echo "Region: $region"
        echo "  VM: $vm_name"
        echo "  IP: $ip"
        echo "  Setup Command:"
        echo "    ssh besuadmin@$ip"
        echo "    wget https://raw.githubusercontent.com/your-repo/terraform/phases/phase1/scripts/setup-besu-node.sh"
        echo "    chmod +x setup-besu-node.sh"
        echo "    sudo ./setup-besu-node.sh besu-node 0 $region"
        echo ""
    fi
done <<< "$BACKEND_VMS"

echo "=========================================="
echo "Setup Instructions"
echo "=========================================="
echo ""
echo "1. Connect to VPN/Bastion to access backend VMs"
echo "2. For each VM, SSH and run the setup script"
echo "3. Verify Besu is running: sudo systemctl status besu.service"
echo "4. Test RPC: curl http://localhost:8545"
echo ""

