@echo off
setlocal

set "PROJECT_DIR=%~dp0.."
set "PROJECT_FILE=%PROJECT_DIR%\AgrarianGame.uproject"
set "UE_ROOT=C:\Program Files\Epic Games\UE_5.7"
set "RUN_UAT=%UE_ROOT%\Engine\Build\BatchFiles\RunUAT.bat"
set "ARCHIVE_DIR=%PROJECT_DIR%\Builds\LinuxGameDevelopment"
set "LOG_DIR=%PROJECT_DIR%\Saved\BuildLogs"
set "LOG_FILE=%LOG_DIR%\PackageLinuxGameServerFallback.log"
set "TARGET_MAP=/Game/Agrarian/Maps/L_GroundZeroTerrain_Test"
set "DEFAULT_LINUX_MULTIARCH_ROOT=C:\UnrealToolchains\v26_clang-20.1.8-rockylinux8"

if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"
if not exist "%ARCHIVE_DIR%" mkdir "%ARCHIVE_DIR%"

if "%LINUX_MULTIARCH_ROOT%"=="" (
  if exist "%DEFAULT_LINUX_MULTIARCH_ROOT%\x86_64-unknown-linux-gnu\bin\clang++.exe" (
    set "LINUX_MULTIARCH_ROOT=%DEFAULT_LINUX_MULTIARCH_ROOT%"
  )
)

if not exist "%RUN_UAT%" (
  echo Unreal Engine 5.7 RunUAT was not found at:
  echo %RUN_UAT%
  exit /b 1
)

if not exist "%PROJECT_FILE%" (
  echo Project file was not found at:
  echo %PROJECT_FILE%
  exit /b 1
)

if "%LINUX_MULTIARCH_ROOT%"=="" (
  echo LINUX_MULTIARCH_ROOT is not set and the default toolchain was not found:
  echo %DEFAULT_LINUX_MULTIARCH_ROOT%
  exit /b 1
)

echo Packaging Agrarian Linux game-server fallback...
echo Archive: %ARCHIVE_DIR%
echo Log: %LOG_FILE%
echo LINUX_MULTIARCH_ROOT=%LINUX_MULTIARCH_ROOT%
echo.

call "%RUN_UAT%" BuildCookRun ^
  -project="%PROJECT_FILE%" ^
  -noP4 ^
  -platform=Linux ^
  -clientconfig=Development ^
  -build ^
  -cook ^
  -stage ^
  -pak ^
  -archive ^
  -archivedirectory="%ARCHIVE_DIR%" ^
  -map=%TARGET_MAP% ^
  -utf8output ^
  -NoUBA > "%LOG_FILE%" 2>&1

set "PACKAGE_EXIT_CODE=%ERRORLEVEL%"
type "%LOG_FILE%"

if not "%PACKAGE_EXIT_CODE%"=="0" (
  echo.
  echo Linux game-server fallback package failed with exit code %PACKAGE_EXIT_CODE%.
  echo Log file: %LOG_FILE%
  exit /b %PACKAGE_EXIT_CODE%
)

echo.
echo Linux game-server fallback package completed successfully.
echo Archive: %ARCHIVE_DIR%
echo.
exit /b 0
