@echo off
setlocal EnableDelayedExpansion
set "ROOT=%~dp0"
set "MANIFEST_NAME=files.sha256"

if not exist "%ROOT%!MANIFEST_NAME!" goto missing_manifest

pushd "%ROOT%"
if errorlevel 1 goto missing_manifest

set "FAILED=0"
for /f "usebackq tokens=1,2 delims=|" %%A in ("%MANIFEST_NAME%") do (
    set "EXPECTED=%%A"
    set "REL=%%B"
    if not exist "!REL!" (
        echo MISSING: !REL!
        set "FAILED=1"
    ) else (
        set "LINE="
        for /f "tokens=* delims=" %%H in ('certutil -hashfile "!REL!" SHA256 ^| findstr /r /i "^[0-9a-f][0-9a-f]"') do (
            set "LINE=%%H"
        )
        set "ACTUAL=!LINE: =!"
        if not defined ACTUAL (
            echo HASH ERROR: !REL!
            set "FAILED=1"
        ) else if /I not "!EXPECTED!"=="!ACTUAL!" (
            echo MISMATCH: !REL!
            echo Expected: !EXPECTED!
            echo Actual:   !ACTUAL!
            set "FAILED=1"
        )
    )
)

popd

if "!FAILED!"=="1" goto verify_failed
echo OK: All files match files.sha256
pause
exit /b 0

:verify_failed
echo FAILED: One or more files do not match.
pause
exit /b 1

:missing_manifest
echo ERROR: Manifest file not found: %ROOT%!MANIFEST_NAME!
pause
exit /b 1
