#!/bin/bash

# Talos ISO download script
# Downloads custom Talos ISO with system extensions for USB boot

set -euo pipefail

# Check if WC_HOME is set
if [ -z "${WC_HOME:-}" ]; then
    echo "Error: WC_HOME environment variable not set. Run \`source .env\`."
    exit 1
fi

CONFIG_FILE="${WC_HOME}/config.yaml"
ISO_DIR="${WC_HOME}/.wildcloud/iso"
FORCE_DOWNLOAD=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --force)
            FORCE_DOWNLOAD=true
            shift
            ;;
        -h|--help)
            echo "Usage: wild-talos-iso [--force]"
            echo ""
            echo "Downloads custom Talos ISO with system extensions for USB boot."
            echo ""
            echo "Options:"
            echo "  --force    Force re-download even if ISO already exists"
            echo "  -h, --help Show this help message"
            echo ""
            echo "This script:"
            echo "  1. Gets schematic ID and Talos version from config.yaml"
            echo "  2. Downloads custom ISO from Talos Image Factory"
            echo "  3. Saves ISO to .wildcloud/iso/ directory"
            echo ""
            echo "The ISO includes extensions configured in config.yaml:"
            echo "  (.cluster.nodes.talos.schematic.customization.systemExtensions)"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

echo "Downloading custom Talos ISO with system extensions..."

# Get Talos version and schematic ID from config
TALOS_VERSION=$(yq eval '.cluster.nodes.talos.version' "$CONFIG_FILE")
SCHEMATIC_ID=$(yq eval '.cluster.nodes.talos.schematicId // ""' "$CONFIG_FILE")

if [ -z "$TALOS_VERSION" ] || [ "$TALOS_VERSION" = "null" ]; then
    echo "Error: No Talos version found in config.yaml at .cluster.nodes.talos.version"
    exit 1
fi

if [ -z "$SCHEMATIC_ID" ] || [ "$SCHEMATIC_ID" = "null" ]; then
    echo "Error: No schematic ID found in config.yaml"
    echo "Run 'wild-talos-schema' first to upload schematic and get ID"
    exit 1
fi

echo "Talos version: $TALOS_VERSION"
echo "Schematic ID: $SCHEMATIC_ID"
echo ""
echo "ISO includes extensions:"
yq eval '.cluster.nodes.talos.schematic.customization.systemExtensions.officialExtensions[]' "$CONFIG_FILE" | sed 's/^/  - /'
echo ""

# Create ISO directory
mkdir -p "$ISO_DIR"

# Define ISO filename and path
ISO_FILENAME="talos-${TALOS_VERSION}-metal-amd64.iso"
ISO_PATH="${ISO_DIR}/${ISO_FILENAME}"

# Check if ISO already exists
if [ -f "$ISO_PATH" ] && [ "$FORCE_DOWNLOAD" = false ]; then
    echo "✅ ISO already exists: $ISO_PATH"
    echo "Use --force to re-download"
    echo ""
    echo "To create a bootable USB:"
    echo "  See docs/node_setup.md for USB creation instructions"
    exit 0
fi

# Download ISO from Image Factory
ISO_URL="https://factory.talos.dev/image/${SCHEMATIC_ID}/${TALOS_VERSION}/metal-amd64.iso"
echo "Downloading ISO from: $ISO_URL"
echo "Saving to: $ISO_PATH"
echo ""

# Download with progress bar
if command -v wget >/dev/null 2>&1; then
    wget --progress=bar:force -O "$ISO_PATH" "$ISO_URL"
elif command -v curl >/dev/null 2>&1; then
    curl -L --progress-bar -o "$ISO_PATH" "$ISO_URL"
else
    echo "Error: Neither wget nor curl is available for downloading"
    exit 1
fi

# Verify download
if [ ! -f "$ISO_PATH" ] || [ ! -s "$ISO_PATH" ]; then
    echo "Error: Download failed or file is empty"
    rm -f "$ISO_PATH"
    exit 1
fi

# Get file size for verification
FILE_SIZE=$(du -h "$ISO_PATH" | cut -f1)

echo ""
echo "✅ Custom Talos ISO downloaded successfully!"
echo ""
echo "ISO Details:"
echo "  File: $ISO_PATH"
echo "  Size: $FILE_SIZE"
echo "  Version: $TALOS_VERSION"
echo "  Extensions: $(yq eval '.cluster.nodes.talos.schematic.customization.systemExtensions.officialExtensions | length' "$CONFIG_FILE") extensions included"
echo "  Auto-wipe: Enabled (will wipe existing Talos installations)"
echo ""
echo "Next steps:"
echo "1. Create bootable USB drive (see docs/node_setup.md)"
echo "2. Boot target machine from USB"
echo "3. Run hardware detection: ./detect-node-hardware.sh <maintenance-ip> <node-number>"
echo "4. Apply machine configuration"
echo ""
echo "USB Creation Quick Reference:"
echo "  Linux:   sudo dd if=$ISO_PATH of=/dev/sdX bs=4M status=progress"
echo "  macOS:   sudo dd if=$ISO_PATH of=/dev/rdiskX bs=4m"
echo "  Windows: Use Rufus, Balena Etcher, or similar tool"