@echo off
if "%1"=="clean" (
    call :CLEAN
    goto :eof
)

echo ----------------------------------------------------
echo:
echo                    BUILDING XIGEN
echo:
echo ----------------------------------------------------

set XIGENVER=v1.1.0
echo xigen version:     %XIGENVER%

echo ----------------------------------------------------
echo                  System checking...
echo ----------------------------------------------------
echo Checking Git...
where /q git
if not %errorlevel% == 0 (
    echo ERROR: git is not found! Check the installation and/or PATH.
    goto FAIL
) else (
    echo ***** Done!
    set GIT=git
)

echo Checking CMake...
where /q cmake
if not %errorlevel% == 0 (
    echo ERROR: cmake is not found! Check the installation and/or PATH.
    goto FAIL
) else (
    echo ***** Done!
    set CMAKE=cmake
)
echo --------------- System checking done ---------------

call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x86
call :DEPS_XIGEN win32 Win32
if not %errorlevel% == 0 goto FAIL

call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
call :DEPS_XIGEN win64 x64
if not %errorlevel% == 0 goto FAIL

echo ----------------------------------------------------
echo             BUILDING XIGEN IS COMPLETED
echo ----------------------------------------------------
echo Output:
echo * %DEPSDIR%\win32\xigen
echo * %DEPSDIR%\win64\xigen
echo ----------------------------------------------------
goto :eof


rem The code below defines functions
:CLEAN
echo Cleaning xigen...
if exist %DEPSDIR%\win32\xigen rmdir /s/q %DEPSDIR%\win32\xigen
if exist %DEPSDIR%\win64\xigen rmdir /s/q %DEPSDIR%\win64\xigen
goto :eof


:DEPS_XIGEN
set DISTARCH=%DEPSDIR%\%1
set ARCH=%2
echo:
echo +++++++++++++ Building xigen for %ARCH%...

if exist %DISTARCH%\xigen rmdir /S /Q %DISTARCH%\xigen
mkdir %DISTARCH%\xigen

set URL_XIGEN="https://github.com/Standa-Optomechanics/xigen.git"

"%GIT%" clone --recursive %URL_XIGEN% %DISTARCH%\xigen -b %XIGENVER%
if not %errorlevel% == 0 goto FAIL
:: We create an empty unistd.h file to avoid warnings in Visual Studio 2022, as this file does not exist in Windows #135151
cd /d "%DISTARCH%\xigen\src"
echo /* Empty file for Windows compatibility */ > unistd.h
cd %DISTARCH%\xigen
if not %errorlevel% == 0 goto FAIL
set GENERATOR=Visual Studio 17 2022
:: We add the /wd4005 flag because in scanner.cc we override INT_MIN and others that are defined in VS 2022 #135151
%CMAKE% -G "%GENERATOR%" -A %ARCH% -DCMAKE_CXX_FLAGS="/wd4005 /EHsc" -DBUILD_TESTING=OFF -DCMAKE_INSTALL_PREFIX=%DISTARCH%\xigen
if not %errorlevel% == 0 goto FAIL
msbuild ALL_BUILD.vcxproj /p:Configuration=%CONFIGURATION% /p:Platform=%ARCH%
if not %errorlevel% == 0 goto FAIL
msbuild INSTALL.vcxproj /p:Configuration=%CONFIGURATION% /p:Platform=%ARCH%
if not %errorlevel% == 0 goto FAIL
cd %BASEDIR%
goto :eof


:FAIL
echo FAIL
exit /B 1
