#\!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-cluster-node-boot-assets-download [options]"
    echo ""
    echo "Generate custom Talos installer image URLs for cluster nodes."
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo ""
    echo "This script will:"
    echo "  - Configure basic cluster settings if needed"
    echo "  - Generate custom Talos installer image URL"
    echo "  - Display the installer URL for PXE boot or ISO creation"
    echo ""
    echo "Requirements:"
    echo "  - Must be run from a wild-cloud directory"
    echo "  - Requires Talos version and schematic ID configuration"
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            usage
            exit 1
            ;;
    esac
done

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    print "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

# Check for required configuration
if [ -z "$(wild-config "cluster.nodes.talos.version")" ] || [ -z "$(wild-config "cluster.nodes.talos.schematicId")" ]; then
    print_header "Talos Configuration Required"
    print_error "Missing required Talos configuration"
    print_info "Please run 'wild-setup' first to configure your cluster"
    print_info "Or set the required configuration manually:"
    print_info "  wild-config-set cluster.nodes.talos.version v1.10.4"
    print_info "  wild-config-set cluster.nodes.talos.schematicId YOUR_SCHEMATIC_ID"
    exit 1
fi

# =============================================================================
# INSTALLER IMAGE GENERATION AND ASSET DOWNLOADING
# =============================================================================

print_header "Talos Installer Image Generation and Asset Download"

# Get Talos version and schematic ID from config
TALOS_VERSION=$(wild-config cluster.nodes.talos.version)
SCHEMATIC_ID=$(wild-config cluster.nodes.talos.schematicId)

print_info "Creating custom Talos installer image..."
print_info "Talos version: $TALOS_VERSION"

# Validate schematic ID
if [ -z "$SCHEMATIC_ID" ] || [ "$SCHEMATIC_ID" = "null" ]; then
    print_error "No schematic ID found in config.yaml"
    print_info "Please run 'wild-setup' first to configure your cluster"
    exit 1
fi

print_info "Schematic ID: $SCHEMATIC_ID"

if [ -f "${WC_HOME}/config.yaml" ] && yq eval '.cluster.nodes.talos.schematic.customization.systemExtensions.officialExtensions' "${WC_HOME}/config.yaml" >/dev/null 2>&1; then
    echo ""
    print_info "Schematic includes:"
    yq eval '.cluster.nodes.talos.schematic.customization.systemExtensions.officialExtensions[]' "${WC_HOME}/config.yaml" | sed 's/^/  - /' || true
    echo ""
fi

# Generate installer image URL
INSTALLER_URL="factory.talos.dev/metal-installer/$SCHEMATIC_ID:$TALOS_VERSION"

print_success "Custom installer image URL generated!"
echo ""
print_info "Installer URL: $INSTALLER_URL"

# =============================================================================
# ASSET DOWNLOADING AND CACHING
# =============================================================================

print_header "Downloading and Caching PXE Boot Assets"

# Create cache directories organized by schematic ID
CACHE_DIR="${WC_HOME}/.wildcloud"
SCHEMATIC_CACHE_DIR="${CACHE_DIR}/node-boot-assets/${SCHEMATIC_ID}"
PXE_CACHE_DIR="${SCHEMATIC_CACHE_DIR}/pxe"
IPXE_CACHE_DIR="${SCHEMATIC_CACHE_DIR}/ipxe"
ISO_CACHE_DIR="${SCHEMATIC_CACHE_DIR}/iso"
mkdir -p "$PXE_CACHE_DIR/amd64"
mkdir -p "$IPXE_CACHE_DIR"
mkdir -p "$ISO_CACHE_DIR"

# Download Talos kernel and initramfs for PXE boot
print_info "Downloading Talos PXE assets..."
KERNEL_URL="https://pxe.factory.talos.dev/image/${SCHEMATIC_ID}/${TALOS_VERSION}/kernel-amd64"
INITRAMFS_URL="https://pxe.factory.talos.dev/image/${SCHEMATIC_ID}/${TALOS_VERSION}/initramfs-amd64.xz"

KERNEL_PATH="${PXE_CACHE_DIR}/amd64/vmlinuz"
INITRAMFS_PATH="${PXE_CACHE_DIR}/amd64/initramfs.xz"

# Function to download with progress
download_asset() {
    local url="$1"
    local path="$2"
    local description="$3"
    
    if [ -f "$path" ]; then
        print_info "$description already cached at $path"
        return 0
    fi
    
    print_info "Downloading $description..."
    print_info "URL: $url"
    
    if command -v wget >/dev/null 2>&1; then
        wget --progress=bar:force -O "$path" "$url"
    elif command -v curl >/dev/null 2>&1; then
        curl -L --progress-bar -o "$path" "$url"
    else
        print_error "Neither wget nor curl is available for downloading"
        return 1
    fi
    
    # Verify download
    if [ ! -f "$path" ] || [ ! -s "$path" ]; then
        print_error "Download failed or file is empty: $path"
        rm -f "$path"
        return 1
    fi
    
    print_success "$description downloaded successfully"
}

# Download Talos PXE assets
download_asset "$KERNEL_URL" "$KERNEL_PATH" "Talos kernel"
download_asset "$INITRAMFS_URL" "$INITRAMFS_PATH" "Talos initramfs"

# Download iPXE bootloader files
print_info "Downloading iPXE bootloader assets..."
download_asset "http://boot.ipxe.org/ipxe.efi" "${IPXE_CACHE_DIR}/ipxe.efi" "iPXE EFI bootloader"
download_asset "http://boot.ipxe.org/undionly.kpxe" "${IPXE_CACHE_DIR}/undionly.kpxe" "iPXE BIOS bootloader"
download_asset "http://boot.ipxe.org/arm64-efi/ipxe.efi" "${IPXE_CACHE_DIR}/ipxe-arm64.efi" "iPXE ARM64 EFI bootloader"

# Download Talos ISO
print_info "Downloading Talos ISO..."
ISO_URL="https://factory.talos.dev/image/${SCHEMATIC_ID}/${TALOS_VERSION}/metal-amd64.iso"
ISO_FILENAME="talos-${TALOS_VERSION}-metal-amd64.iso"
ISO_PATH="${ISO_CACHE_DIR}/${ISO_FILENAME}"
download_asset "$ISO_URL" "$ISO_PATH" "Talos ISO"

echo ""
print_success "All assets downloaded and cached!"
echo ""
print_info "Cached assets for schematic $SCHEMATIC_ID:"
echo "  Talos kernel:     $KERNEL_PATH"
echo "  Talos initramfs:  $INITRAMFS_PATH"
echo "  Talos ISO:        $ISO_PATH"
echo "  iPXE EFI:         ${IPXE_CACHE_DIR}/ipxe.efi"
echo "  iPXE BIOS:        ${IPXE_CACHE_DIR}/undionly.kpxe"
echo "  iPXE ARM64:       ${IPXE_CACHE_DIR}/ipxe-arm64.efi"
echo ""
print_info "Cache location: $SCHEMATIC_CACHE_DIR"
echo ""
print_info "Use these assets for:"
echo "  - PXE boot: Use kernel and initramfs from cache"
echo "  - USB creation: Use ISO file for dd or imaging tools"
echo "    Example: sudo dd if=$ISO_PATH of=/dev/sdX bs=4M status=progress"
echo "  - Custom installer: https://$INSTALLER_URL"
echo ""
print_success "Installer image generation and asset caching completed!"