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

rem   build.bat         build StartupManager.exe
rem   build.bat /test   build, then build and run the smoke test
rem                     (needs the exe - it drives the real StartupManager.exe)

set RUN_TEST=0
if /i "%~1"=="/test" set RUN_TEST=1
if /i "%~1"=="-test" set RUN_TEST=1
if /i "%~1"=="test"  set RUN_TEST=1

if exist StartupManager.exe del StartupManager.exe

where g++ >nul 2>nul
if not errorlevel 1 (
    echo Building with MinGW g++ (static runtime)
    g++ -O2 -static -mwindows -municode ^
        StartupManager.cpp -o StartupManager.exe ^
        -lcomctl32 -ladvapi32 -lshell32 -lole32 -luuid -lcomdlg32 -lgdi32 -luser32
    if errorlevel 1 goto :fail
    echo.
    echo OK -^> StartupManager.exe
    if "%RUN_TEST%"=="1" (
        echo.
        echo Building smoke test
        g++ -O2 -static smoketest.cpp -o smoketest.exe ^
            -lcomctl32 -ladvapi32 -lshell32 -lgdi32 -luser32
        if errorlevel 1 goto :fail
        echo.
        smoketest.exe
        if errorlevel 1 goto :fail
    ) else (
        echo Run "build.bat /test" to also build and run the smoke test.
    )
    goto :eof
)

where cl >nul 2>nul
if not errorlevel 1 (
    echo Building with MSVC cl (static CRT)
    cl /O2 /EHsc /MT /D _UNICODE /D UNICODE StartupManager.cpp ^
       comctl32.lib advapi32.lib shell32.lib ole32.lib uuid.lib comdlg32.lib gdi32.lib user32.lib ^
       /link /SUBSYSTEM:WINDOWS
    if errorlevel 1 goto :fail
    echo OK -^> StartupManager.exe
    if "%RUN_TEST%"=="1" (
        echo.
        echo Building smoke test
        cl /O2 /EHsc /MT /D _UNICODE /D UNICODE smoketest.cpp ^
           comctl32.lib advapi32.lib shell32.lib gdi32.lib user32.lib ^
           /link /SUBSYSTEM:CONSOLE
        if errorlevel 1 goto :fail
        echo.
        smoketest.exe
        if errorlevel 1 goto :fail
    ) else (
        echo Run "build.bat /test" to also build and run the smoke test.
    )
    goto :eof
)

echo ERROR: no C++ compiler found. Install MinGW-w64 or Visual Studio.
exit /b 1

:fail
echo.
echo BUILD FAILED
exit /b 1
