@echo off
setlocal enabledelayedexpansion
title YUMI GUI — Nuitka Windows Build Script

set "SCRIPT_DIR=%~dp0"
set "SOURCE=%SCRIPT_DIR%yumi_gui.py"
set "OUTPUT_EXE=yumi_py.exe"

if not exist "%SOURCE%" (
    echo ERROR: yumi_gui.py not found in %SCRIPT_DIR%
    pause
    exit /b 1
)

:: ── Add build folder to Defender exclusions ──────────────────────────────────
:: Defender sometimes briefly locks the output exe while Nuitka is embedding
:: icon/version resources, causing a harmless retry. Adding an exclusion for
:: the script directory prevents the lock. Silently ignored if Defender isn't
:: running or the user lacks permission.
PowerShell -Command "Add-MpPreference -ExclusionPath '%SCRIPT_DIR%' -ErrorAction SilentlyContinue" >nul 2>nul

:: ── Verify Python 3.9 ─────────────────────────────────────────────────────────
py -3.9 -c "import sys" >nul 2>nul
if %errorlevel% neq 0 (
    echo ERROR: Python 3.9 not found. Install it and try again.
    pause
    exit /b 1
)

:: ── Install/upgrade Nuitka silently ──────────────────────────────────────────
:: certifi is included here (and bundled below) for the same reason it was
:: added to the Linux builder scripts: _https_context() in yumi_gui.py prefers
:: certifi's CA bundle over the OS trust store. Without it, "Check for Updates"
:: falls back to Windows' own trust store, which on an unpatched/locked-down
:: Windows 10 box can be missing current roots and fail TLS verification -
:: something that showed up as a misleading "no internet connection" error
:: because the old code swallowed the real exception. certifi sidesteps that
:: dependency on the local machine's cert store entirely.
py -3.9 -m pip install --quiet --upgrade nuitka ordered-set zstandard certifi >nul 2>nul

:: ── Check tkinter ─────────────────────────────────────────────────────────────
py -3.9 -c "import tkinter" >nul 2>nul
if %errorlevel% neq 0 (
    echo ERROR: tkinter missing from this Python installation.
    pause
    exit /b 1
)

:: ── Assemble data file flags ──────────────────────────────────────────────────
:: All existence checks use single-line if (no parenthetical block) so that
:: parens in %SCRIPT_DIR% (e.g. "Downloads\yumi-py (1)\") never prematurely
:: close a block. Inside multi-line blocks, !SCRIPT_DIR! (delayed expansion)
:: is used for the same reason — it fires after block parsing.
set "DATA_FLAGS="

if exist "%SCRIPT_DIR%distros.json" (
    set DATA_FLAGS=!DATA_FLAGS! "--include-data-files=!SCRIPT_DIR!distros.json=distros.json"
) else echo WARNING: distros.json not found - it will not be bundled.

if exist "%SCRIPT_DIR%YUMI-Copying.txt" (
    set DATA_FLAGS=!DATA_FLAGS! "--include-data-files=!SCRIPT_DIR!YUMI-Copying.txt=YUMI-Copying.txt"
) else echo WARNING: YUMI-Copying.txt not found - it will not be bundled.

if exist "%SCRIPT_DIR%yumi_icon.png" (
    set DATA_FLAGS=!DATA_FLAGS! "--include-data-files=!SCRIPT_DIR!yumi_icon.png=yumi_icon.png"
) else echo WARNING: yumi_icon.png not found - the app window/header icon will fall back to the default Tk icon.

:: NOTE: --include-data-dir silently drops .exe/.dll/.py files from a directory tree
:: (Nuitka treats them as "data", not data, and ignores them with no warning).
:: YUMI4Windows\tools contains mke2fs.exe / wimlib-imagex.exe, and Ventoy zips may
:: contain binaries too, so we use --include-raw-dir instead, which copies the
:: folder byte-for-byte with no filtering at all.
if exist "%SCRIPT_DIR%YUMI4Windows" (
    set DATA_FLAGS=!DATA_FLAGS! "--include-raw-dir=!SCRIPT_DIR!YUMI4Windows=YUMI4Windows"
) else echo WARNING: YUMI4Windows folder not found - it will not be bundled.

:: yumi_gui.py only touches YUMI4Linux\YUMIFILES on Windows (the YUMI boot-menu
:: theme assets it copies onto the drive). The rest of YUMI4Linux (YUMI2Disk.sh,
:: the ventoy-<ver> Linux/aarch64/mips64el binaries, boot images) is Linux-only
:: and not used at runtime on Windows at all, so only YUMIFILES is bundled here
:: to keep the Windows binary footprint down.
if exist "%SCRIPT_DIR%YUMI4Linux\YUMIFILES" (
    set DATA_FLAGS=!DATA_FLAGS! "--include-raw-dir=!SCRIPT_DIR!YUMI4Linux\YUMIFILES=YUMI4Linux\YUMIFILES"
) else echo WARNING: YUMI4Linux\YUMIFILES folder not found - the YUMI boot-menu theme will not be bundled, so prepared drives will keep the stock Ventoy theme.

if exist "%SCRIPT_DIR%yumi.ico" (
    set DATA_FLAGS=!DATA_FLAGS! "--include-data-files=!SCRIPT_DIR!yumi.ico=yumi.ico"
)

if not exist "%SCRIPT_DIR%YUMI4Windows\tools\mke2fs.exe" echo WARNING: YUMI4Windows\tools\mke2fs.exe not found - persistence files will not be ext4-formatted.
if not exist "%SCRIPT_DIR%YUMI4Windows\tools\wimlib\wimlib-imagex.exe" echo WARNING: YUMI4Windows\tools\wimlib\wimlib-imagex.exe not found - VHD installs will use system DISM only.
if not exist "%SCRIPT_DIR%YUMI4Windows\AutoUnattend.xml" echo WARNING: YUMI4Windows\AutoUnattend.xml not found - VHD installs will skip unattended setup.

:: ── Verify a bundled Windows Ventoy zip exists ─────────────────────────────────
:: yumi_gui.py now globs YUMI4Windows\tools\ventoy-*-windows.zip directly at
:: runtime (no version-string matching against YUMI4Linux required anymore).
set "VENTOY_ZIP_FOUND="
if exist "%SCRIPT_DIR%YUMI4Windows\tools" (
    for /f "delims=" %%Z in ('dir /b "%SCRIPT_DIR%YUMI4Windows\tools\ventoy-*-windows.zip" 2^>nul') do (
        if not defined VENTOY_ZIP_FOUND set "VENTOY_ZIP_FOUND=%%Z"
    )
)
if not defined VENTOY_ZIP_FOUND (
    echo WARNING: No YUMI4Windows\tools\ventoy-*-windows.zip found - Windows Ventoy install/update will fail at runtime.
) else (
    echo Found Windows Ventoy zip: !VENTOY_ZIP_FOUND!
)

:: ── Build ─────────────────────────────────────────────────────────────────────
echo Building %OUTPUT_EXE% ...
cd /d "%SCRIPT_DIR%"
if exist "%OUTPUT_EXE%" del "%OUTPUT_EXE%"

:: Use a single-line if for the existence test so that (1) or other parens in
:: %SCRIPT_DIR% cannot prematurely terminate a parenthetical block at parse time.
:: Inside the second if block, !SCRIPT_DIR! (delayed expansion) is used for the
:: same reason — delayed expansion fires after block parsing, so parens inside
:: the path are never seen as block delimiters.
set "ICON_FLAG="
if exist "%SCRIPT_DIR%yumi.ico" set "ICON_FLAG=found"
if defined ICON_FLAG (
    set ICON_FLAG="--windows-icon-from-ico=!SCRIPT_DIR!yumi.ico"
    echo Using icon: !SCRIPT_DIR!yumi.ico
) else (
    echo WARNING: yumi.ico not found - exe will use the generic Windows icon.
)

py -3.9 -m nuitka ^
    --onefile ^
    --onefile-tempdir-spec="{CACHE_DIR}\YUMI\runtime" ^
    --enable-plugin=tk-inter ^
    --include-package-data=certifi ^
    --windows-console-mode=disable ^
    --windows-uac-admin ^
    --windows-product-name="YUMI" ^
    --windows-company-name="YUMI Project" ^
    --windows-product-version="1.0.0.0" ^
    --windows-file-version="1.0.0.0" ^
    --windows-file-description="YUMI Multiboot USB Creator" ^
    !ICON_FLAG! ^
    --output-filename="%OUTPUT_EXE%" ^
    --assume-yes-for-downloads ^
    --show-progress ^
    --remove-output ^
    !DATA_FLAGS! ^
    "%SOURCE%"

if exist "%OUTPUT_EXE%" (
    echo.
    echo Done: %CD%\%OUTPUT_EXE%
    echo Run as Administrator or it will prompt for UAC elevation automatically.
    echo.
    echo Tip: if you ever suspect files are missing from the bundle again, rerun
    echo this script's nuitka command with --mode=standalone instead of --onefile,
    echo then compare the resulting yumi_gui.dist\YUMI4Windows folder file-for-file
    echo against the source YUMI4Windows folder ^(e.g. with a recursive dir /s /b
    echo or a diff tool^) before switching back to --onefile.
) else (
    echo.
    echo ERROR: Build failed - %OUTPUT_EXE% was not created.
)
pause
endlocal
