#!/bin/bash

# Parse command line arguments
INSTALL_MODE=false
SCHEMATIC_ID_OVERRIDE=""
while [[ $# -gt 0 ]]; do
    case $1 in
        --install)
            INSTALL_MODE=true
            shift
            ;;
        --schematic-id)
            SCHEMATIC_ID_OVERRIDE="$2"
            shift 2
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--install] [--schematic-id SCHEMATIC_ID]"
            echo "  --install              Copy bundle to DNSMasq server and run installation"
            echo "  --schematic-id ID      Use specific schematic ID instead of config default"
            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

# ---

SOURCE_DIR="${WC_ROOT}/setup/dnsmasq"
DNSMASQ_SETUP_DIR="${WC_HOME}/setup/dnsmasq"
BUNDLE_DIR="${DNSMASQ_SETUP_DIR}/setup-bundle"
mkdir -p "${BUNDLE_DIR}"


# Create local templates.

if [ -d "${DNSMASQ_SETUP_DIR}" ]; then
    echo "Warning: ${DNSMASQ_SETUP_DIR} already exists"
    read -p "Overwrite? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Skipping dnsmasq setup"
    else
        rm -rf "${DNSMASQ_SETUP_DIR}"
        cp -r "${SOURCE_DIR}" "${DNSMASQ_SETUP_DIR}"
        find "${DNSMASQ_SETUP_DIR}" -type f \( -name "*.yaml" -o -name "*.ipxe" -o -name "*.conf" \) | while read -r file; do
            echo "Processing: ${file}"
            wild-compile-template < "${file}" > "${file}.tmp" && mv "${file}.tmp" "${file}"
        done
        echo "Successfully created dnsmasq setup files from templates."
    fi
else
    cp -r "${SOURCE_DIR}" "${DNSMASQ_SETUP_DIR}"
    find "${DNSMASQ_SETUP_DIR}" -type f \( -name "*.yaml" -o -name "*.ipxe" -o -name "*.conf" \) | while read -r file; do
        echo "Processing: ${file}"
        wild-compile-template < "${file}" > "${file}.tmp" && mv "${file}.tmp" "${file}"
    done
    echo "Successfully created dnsmasq setup files from templates."
fi

# Create setup bundle.

# Copy iPXE bootloader to ipxe-web from cached assets.
echo "Copying Talos PXE assets from cache..."
PXE_WEB_ROOT="${BUNDLE_DIR}/ipxe-web"
mkdir -p "${PXE_WEB_ROOT}/amd64"
cp "${DNSMASQ_SETUP_DIR}/boot.ipxe" "${PXE_WEB_ROOT}/boot.ipxe"

# Get schematic ID from override or config
if [ -n "$SCHEMATIC_ID_OVERRIDE" ]; then
    SCHEMATIC_ID="$SCHEMATIC_ID_OVERRIDE"
    echo "Using schematic ID from command line: $SCHEMATIC_ID"
else
    SCHEMATIC_ID=$(wild-config cluster.nodes.talos.schematicId)
    if [ -z "$SCHEMATIC_ID" ] || [ "$SCHEMATIC_ID" = "null" ]; then
        echo "Error: No schematic ID found in config"
        echo "Please run 'wild-setup' first to configure your cluster"
        echo "Or specify one with --schematic-id option"
        exit 1
    fi
    echo "Using schematic ID from config: $SCHEMATIC_ID"
fi

# Define cache directories using new structure
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"

# Check if cached assets exist
KERNEL_CACHE_PATH="${PXE_CACHE_DIR}/amd64/vmlinuz"
INITRAMFS_CACHE_PATH="${PXE_CACHE_DIR}/amd64/initramfs.xz"

if [ ! -f "${KERNEL_CACHE_PATH}" ] || [ ! -f "${INITRAMFS_CACHE_PATH}" ]; then
    echo "Error: Talos PXE assets not found in cache for schematic ID: ${SCHEMATIC_ID}"
    echo "Expected locations:"
    echo "  Kernel: ${KERNEL_CACHE_PATH}"
    echo "  Initramfs: ${INITRAMFS_CACHE_PATH}"
    echo ""
    echo "Please run 'wild-cluster-node-boot-assets-download' first to download and cache the assets."
    exit 1
fi

# Copy Talos PXE assets from cache
echo "Copying Talos kernel from cache..."
cp "${KERNEL_CACHE_PATH}" "${PXE_WEB_ROOT}/amd64/vmlinuz"
echo "✅ Talos kernel copied from cache"

echo "Copying Talos initramfs from cache..."
cp "${INITRAMFS_CACHE_PATH}" "${PXE_WEB_ROOT}/amd64/initramfs.xz"
echo "✅ Talos initramfs copied from cache"

# Copy iPXE bootloader files from cache
echo "Copying iPXE bootloader files from cache..."
FTPD_DIR="${BUNDLE_DIR}/pxe-ftpd"
mkdir -p "${FTPD_DIR}"

# Check if iPXE assets exist in cache
IPXE_EFI_CACHE="${IPXE_CACHE_DIR}/ipxe.efi"
IPXE_BIOS_CACHE="${IPXE_CACHE_DIR}/undionly.kpxe"
IPXE_ARM64_CACHE="${IPXE_CACHE_DIR}/ipxe-arm64.efi"

if [ ! -f "${IPXE_EFI_CACHE}" ] || [ ! -f "${IPXE_BIOS_CACHE}" ] || [ ! -f "${IPXE_ARM64_CACHE}" ]; then
    echo "Error: iPXE bootloader assets not found in cache for schematic ID: ${SCHEMATIC_ID}"
    echo "Expected locations:"
    echo "  iPXE EFI: ${IPXE_EFI_CACHE}"
    echo "  iPXE BIOS: ${IPXE_BIOS_CACHE}"
    echo "  iPXE ARM64: ${IPXE_ARM64_CACHE}"
    echo ""
    echo "Please run 'wild-cluster-node-boot-assets-download' first to download and cache the assets."
    exit 1
fi

# Copy iPXE assets from cache
cp "${IPXE_EFI_CACHE}" "${FTPD_DIR}/ipxe.efi"
cp "${IPXE_BIOS_CACHE}" "${FTPD_DIR}/undionly.kpxe"
cp "${IPXE_ARM64_CACHE}" "${FTPD_DIR}/ipxe-arm64.efi"
echo "✅ iPXE bootloader files copied from cache"


cp "${DNSMASQ_SETUP_DIR}/nginx.conf" "${BUNDLE_DIR}/nginx.conf"
cp "${DNSMASQ_SETUP_DIR}/dnsmasq.conf" "${BUNDLE_DIR}/dnsmasq.conf"
cp "${DNSMASQ_SETUP_DIR}/setup.sh" "${BUNDLE_DIR}/setup.sh"

# Copy setup bundle to DNSMasq server and install (only if --install flag is provided)
if [ "$INSTALL_MODE" = true ]; then
    echo "Installing DNSMasq setup on remote server..."
    
    SERVER_HOST=$(wild-config cloud.dns.ip) || exit 1
    SETUP_DIR="${WC_HOME}/setup/dnsmasq/setup-bundle"
    DESTINATION_DIR="~/dnsmasq-setup"

    echo "Copying DNSMasq setup files to ${SERVER_HOST}:${DESTINATION_DIR}..."
    scp -r ${SETUP_DIR}/* root@${SERVER_HOST}:${DESTINATION_DIR}

    # Run setup script on the DNSMasq server.
    echo "Running setup script on ${SERVER_HOST}..."
    ssh root@${SERVER_HOST} "cd ${DESTINATION_DIR} && ./setup.sh" || {
        echo "Error: Failed to run setup script on ${SERVER_HOST}"
        exit 1
    }
    
    echo "DNSMasq installation completed successfully on ${SERVER_HOST}"
else
    echo "DNSMasq setup bundle created successfully at ${BUNDLE_DIR}"
    echo "Run with --install flag to copy bundle to server and install"
fi