@echo off
setlocal

rem Build script for mpq_extractor GDExtension on Windows.
rem Requires Visual Studio 2022 with the C++ workload installed.

set BUILD_TYPE=%1
if "%BUILD_TYPE%"=="" set BUILD_TYPE=Release

set SCRIPT_DIR=%~dp0
if "%SCRIPT_DIR:~-1%"=="\" set SCRIPT_DIR=%SCRIPT_DIR:~0,-1%
set BUILD_DIR=%SCRIPT_DIR%\build

echo [mpq_extractor] BUILD_TYPE=%BUILD_TYPE%

rem Locate cmake.exe, first from PATH and then from common VS2022 installs.
set VS_CMAKE=
for /f "delims=" %%i in ('where cmake 2^>nul') do (
    set VS_CMAKE=%%i
    goto :cmake_found
)

set VSCMAKE_GUESS=C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe
if exist "%VSCMAKE_GUESS%" (
    set VS_CMAKE=%VSCMAKE_GUESS%
    goto :cmake_found
)

set VSCMAKE_GUESS=C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe
if exist "%VSCMAKE_GUESS%" (
    set VS_CMAKE=%VSCMAKE_GUESS%
    goto :cmake_found
)

set VSCMAKE_GUESS=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe
if exist "%VSCMAKE_GUESS%" (
    set VS_CMAKE=%VSCMAKE_GUESS%
    goto :cmake_found
)

echo ERROR: cmake.exe not found.
echo Install CMake or add it to PATH.
exit /b 1

:cmake_found
echo [mpq_extractor] cmake: %VS_CMAKE%

rem Initialize submodules when needed.
if not exist "%SCRIPT_DIR%\..\..\third_party\godot-cpp\CMakeLists.txt" (
    echo [mpq_extractor] Initializing submodules...
    cd /d "%SCRIPT_DIR%\..\.."
    git submodule update --init --recursive
    if errorlevel 1 (
        echo ERROR: git submodule update failed.
        exit /b 1
    )
    cd /d "%SCRIPT_DIR%"
)

rem Configure.
"%VS_CMAKE%" -S "%SCRIPT_DIR%" -B "%BUILD_DIR%" -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=%BUILD_TYPE%
if errorlevel 1 (
    echo ERROR: cmake configure failed.
    exit /b 1
)

rem Build.
"%VS_CMAKE%" --build "%BUILD_DIR%" --config %BUILD_TYPE% --parallel
if errorlevel 1 (
    echo ERROR: cmake build failed.
    exit /b 1
)

echo.
echo [mpq_extractor] Done. DLL is in:
echo   %SCRIPT_DIR%\..\..\addons\mpq_extractor\bin\

endlocal
