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

echo ----------------------------------------------------
echo:
echo                   BUILDING LIBXIMC
echo:
echo ----------------------------------------------------

echo ----------------------------------------------------
echo                  System checking...
echo ----------------------------------------------------
echo Checking libximc sources that had to be generated by xigen...
set MISSING_FILES_DETECTED=false
for %%F in (%LIBXIMC_INC_DIR%\ximc.h,
    %LIBXIMC_SRC_DIR%\ximc-gen.h,
    %LIBXIMC_SRC_DIR%\ximc-gen.c,
    %LIBXIMC_SRC_DIR%\libximc.def,
    %LIBXIMC_SRC_DIR%\fwprotocol.h,
    %LIBXIMC_SRC_DIR%\fwprotocol.c) do (
        if not exist %%F (
            echo %%F cannot be found. ERROR!
            set MISSING_FILES_DETECTED=true
        ) else (
            echo %%F is found.
        )
)
if "%MISSING_FILES_DETECTED%"=="true" goto FAIL

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 --------------- System checking done ---------------

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

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

echo ----------------------------------------------------
echo             BUILDING LIBXIMC IS COMPLETED
echo ----------------------------------------------------
echo Output:
echo * %DISTDIR%\ximc\win32
echo * %DISTDIR%\ximc\win64
echo ----------------------------------------------------
goto :eof


rem The code below defines functions
:CLEAN
echo Cleaning libximc...
if exist %BASEDIR%\%CONFIGURATION%-Win32    rmdir %BASEDIR%\%CONFIGURATION%-Win32   /s/q
if exist %BASEDIR%\%CONFIGURATION%-x64      rmdir %BASEDIR%\%CONFIGURATION%-x64     /s/q
goto :eof


:LIBXIMC
set DISTARCH=%DISTDIR%\ximc\%1
set ARCH=%2
echo:
echo +++++++++++++ Building libximc for %ARCH%...
set BINDIR=%CONFIGURATION%-%ARCH%

if not exist %DISTARCH% mkdir %DISTARCH%
if not %errorlevel% == 0 goto FAIL

msbuild libximc.sln /p:Configuration=%CONFIGURATION% /p:Platform=%ARCH% /t:libximc
if not %errorlevel% == 0 goto FAIL
copy %BINDIR%\libximc.dll       %DISTARCH%
if not %errorlevel% == 0 goto FAIL
copy %BINDIR%\libximc.lib       %DISTARCH%
if not %errorlevel% == 0 goto FAIL
copy libximc\src\libximc.def    %DISTARCH%
if not %errorlevel% == 0 goto FAIL
copy libximc\include\ximc.h     %DISTARCH%
if not %errorlevel% == 0 goto FAIL
if not "%CONFIGURATION%"=="Debug" goto :SKIP_PDB_COPY_LIBXIMC
copy %BINDIR%\*.pdb             %DISTARCH%
if not %errorlevel% == 0 goto FAIL
:SKIP_PDB_COPY_LIBXIMC
goto :eof


:FAIL
echo FAIL
exit /B 1
