@echo off
setlocal EnableExtensions
cd /d "%~dp0"

set "ISO=linux-ai-1.0-star-cinnamon-amd64.iso"
set "PREFIX=linux-ai-1.0-star-cinnamon-amd64.iso.part"
set "EXPECTED=17674146507f78a5724af5d69a7be1e36589e919f48673479e87c4d25118af91"

echo Linux-AI OS ISO Rebuild Utility
echo ================================
echo.

set "MISSING=0"
for %%N in (00 01 02 03 04 05 06 07 08 09 10 11 12 13) do (
    if not exist "%PREFIX%%%N" (
        echo MISSING: %PREFIX%%%N
        set "MISSING=1"
    )
)

if "%MISSING%"=="1" (
    echo.
    echo ERROR: One or more download parts are missing.
    echo Download all parts ^(part00 through part13^) into this folder and run this file again.
    echo.
    pause
    exit /b 1
)

echo All 14 parts are present.
echo Rebuilding %ISO% ...
if exist "%ISO%" del /f /q "%ISO%"

copy /b "%PREFIX%00"+"%PREFIX%01"+"%PREFIX%02"+"%PREFIX%03"+"%PREFIX%04"+"%PREFIX%05"+"%PREFIX%06"+"%PREFIX%07"+"%PREFIX%08"+"%PREFIX%09"+"%PREFIX%10"+"%PREFIX%11"+"%PREFIX%12"+"%PREFIX%13" "%ISO%" >nul
if errorlevel 1 (
    echo.
    echo ERROR: Windows could not rebuild the ISO.
    echo Make sure all files are in the same folder and try again.
    echo.
    pause
    exit /b 2
)

echo.
echo Verifying SHA256 checksum...
set "ACTUAL="
for /f "skip=1 tokens=*" %%H in ('certutil -hashfile "%ISO%" SHA256 ^| findstr /r /v "hash CertUtil"') do if not defined ACTUAL set "ACTUAL=%%H"
set "ACTUAL=%ACTUAL: =%"

echo Expected: %EXPECTED%
echo Actual:   %ACTUAL%
echo.

if /I "%ACTUAL%"=="%EXPECTED%" (
    echo ============================================================
    echo  SUCCESS!
    echo.
    echo  Linux-AI OS has been reconstructed successfully.
    echo  SHA256 VERIFIED
    echo.
    echo  Your ISO is ready:
    echo  %ISO%
    echo ============================================================
    echo.
    pause
    exit /b 0
) else (
    echo ============================================================
    echo  VERIFICATION FAILED
    echo.
    echo  The reconstructed ISO does NOT match the official checksum.
    echo  DO NOT use this ISO to create installation media.
    echo  Re-download any questionable or incomplete part and try again.
    echo ============================================================
    echo.
    pause
    exit /b 3
)
