#!/usr/bin/env bash

# Setup cloud-init script for Besu nodes
# This script creates a cloud-init configuration file for VM deployment

set -e

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

# Configuration
NODE_TYPE="${1:-validator}"
NODE_INDEX="${2:-0}"
OUTPUT_FILE="${3:-/tmp/besu-cloud-init.yaml}"


log_success "Generating cloud-init configuration for $NODE_TYPE-$NODE_INDEX..."

# Create cloud-init file
cat > "$OUTPUT_FILE" <<'EOF'
#cloud-config
# Cloud-init configuration for Besu node setup

package_update: true
package_upgrade: true

packages:
  - apt-transport-https
  - ca-certificates
  - curl
  - gnupg
  - lsb-release
  - jq
  - wget
  - unzip

write_files:
  - path: /opt/besu/setup.sh
    content: |
      #!/bin/bash
      set -e
      echo "Setting up Besu node..."
      
      # Install Docker
      if ! command -v docker &> /dev/null; then
        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
        echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
        apt-get update
        apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
        systemctl enable docker
        systemctl start docker
        usermod -aG docker $USER
      fi
      
      # Create directories
      mkdir -p /opt/besu/{data,config,keys,logs}
      chown -R $USER:$USER /opt/besu
      
      echo "Setup complete!"
    permissions: '0755'
    owner: root:root

runcmd:
  - /opt/besu/setup.sh
  - systemctl daemon-reload

final_message: "Besu node setup complete"
EOF

log_success "✓ Cloud-init configuration created: $OUTPUT_FILE"

