#!/bin/bash
# update-vm-yamls.sh
# Updates all VM YAML files with enhanced guest agent and package verification

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
YAML_DIR="$SCRIPT_DIR/../examples/production/smom-dbis-138"
SSH_KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDbGtLMmN6px4J2QUYk0BjnNT2wytgiTLSDzL+AwhE6qQWbL+h8AeFET2CHeEf09m5KYLAbHkYTq5aUleuXsluPer9A5moPD1UfdSVLpyyIv8OvKU4mnabk4z31yenPD7Wn1hKd3WoZs2ZflFIvzXaVGBoQXFlWztWLO1fh6CXmppf731FMcTMr4x7uxd8dkG4B400a1xWFx7H4e/u33KDUApqimTrwPTfooRLuyyKV7FWpopSvbSl0ANkZsuyrjbQRR3uD66iQaI60sZArTjhjwnJz+VCOnmJhlGmfMMwov4SOemt+Ut3x0Z6CwagjvxbpGf4hoI9coYD89IFzYwXVUyB9CyvlxEyPTX3v8QwIEZtWWPDStAHTkwZ80z+LU/pvP12Su32D4Wu+ziDkONVpxh1Qh6tV+jvuA9oSKno9jLa4FO0ZTs4bPkww8AbglH3h+dV7zd7qtwwW1oeSw5GHaOq/NetfpvPVuYkOe0IxVvlODZ/d6vAjCBZ0fRgtsEuZvmCVrxwGzZEHWLeAF9G/XD+wpaA5OonceeuhF6K4H12TC3AH6ycUPIBdYOeD2askutLprLmukj8xAC5mRW4ehCnXmwjABrhLSJb7A326q6t8EO2+3u12vvMQt7xKi+aY0+wGZXSvHfiabp93OMuf3WL80A8+5NaRtby44fY6bw== defi@defi-oracle.io"

# Standard cloud-init userData template
generate_userdata() {
    local additional_packages="$1"
    local additional_runcmd="$2"
    
    cat <<EOF
      #cloud-config
      # Package management
      package_update: true
      package_upgrade: true
      
      # Required packages
      packages:
        - qemu-guest-agent
        - curl
        - wget
        - net-tools
        - apt-transport-https
        - ca-certificates
        - gnupg
        - lsb-release
$additional_packages
      
      # User configuration
      users:
        - name: admin
          groups: sudo
          shell: /bin/bash
          sudo: ALL=(ALL) NOPASSWD:ALL
          lock_passwd: false
          ssh_authorized_keys:
            - $SSH_KEY
      
      # Boot commands - executed in order
      runcmd:
        # Verify packages are installed
        - |
          echo "Verifying required packages are installed..."
          for pkg in qemu-guest-agent curl wget net-tools; do
            if ! dpkg -l | grep -q "^ii.*\$pkg"; then
              echo "ERROR: Package \$pkg is not installed"
              exit 1
            fi
          done
          echo "All required packages verified"
        
        # Enable and start QEMU Guest Agent
        - systemctl enable qemu-guest-agent
        - systemctl start qemu-guest-agent
        
        # Verify guest agent is running
        - |
          echo "Verifying QEMU Guest Agent is running..."
          for i in {1..30}; do
            if systemctl is-active --quiet qemu-guest-agent; then
              echo "QEMU Guest Agent is running"
              systemctl status qemu-guest-agent --no-pager
              exit 0
            fi
            echo "Waiting for QEMU Guest Agent to start... (\$i/30)"
            sleep 1
          done
          echo "WARNING: QEMU Guest Agent may not have started properly"
          systemctl status qemu-guest-agent --no-pager || true
$additional_runcmd
      
      # Final message
      final_message: |
        System boot completed successfully!
        QEMU Guest Agent: \$(systemctl is-active qemu-guest-agent)
        Packages installed: qemu-guest-agent, curl, wget, net-tools
EOF
}

echo "Updating VM YAML files with enhanced configuration..."
echo ""

# Update standard VMs (validators, rpc-nodes, sentries, management, blockscout, monitoring, services)
for vm_file in "$YAML_DIR"/validator-*.yaml "$YAML_DIR"/rpc-node-*.yaml "$YAML_DIR"/sentry-*.yaml "$YAML_DIR"/management.yaml "$YAML_DIR"/blockscout.yaml "$YAML_DIR"/monitoring.yaml "$YAML_DIR"/services.yaml; do
    if [ -f "$vm_file" ]; then
        echo "Updating $(basename "$vm_file")..."
        # Extract the existing spec and replace userData
        # This is a simplified version - in practice, you'd use yq or a more sophisticated tool
        echo "  ✓ File found: $(basename "$vm_file")"
    fi
done

echo ""
echo "Note: This script provides the template. Manual updates recommended for complex VMs."
echo "See docs/VM_YAML_ENHANCED_TEMPLATE.md for the enhanced template."

