@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 "BUILD_BAT=%UE_ROOT%\Engine\Build\BatchFiles\Build.bat"
set "ARCHIVE_DIR=%PROJECT_DIR%\Builds\LinuxServerDevelopment"
set "LOG_DIR=%PROJECT_DIR%\Saved\BuildLogs"
set "LOG_FILE=%LOG_DIR%\BuildLinuxDedicatedServer.log"
set "TARGET_MAP=/Game/Agrarian/Maps/L_GroundZeroTerrain_Test"

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

if not exist "%BUILD_BAT%" (
  echo Unreal Engine 5.7 Build.bat was not found at:
  echo %BUILD_BAT%
  exit /b 1
)

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
)

echo Building Agrarian Linux dedicated server...
echo Archive: %ARCHIVE_DIR%
echo Log: %LOG_FILE%
echo.
echo This requires Epic's Linux cross-compile toolchain for Unreal 5.7 on Windows-Builder.
echo.

call "%BUILD_BAT%" AgrarianGameServer Linux Development -Project="%PROJECT_FILE%" -WaitMutex -NoUBA > "%LOG_FILE%" 2>&1
set "BUILD_EXIT_CODE=%ERRORLEVEL%"
type "%LOG_FILE%"

if not "%BUILD_EXIT_CODE%"=="0" (
  echo.
  echo Dedicated server target build failed with exit code %BUILD_EXIT_CODE%.
  echo Log file: %LOG_FILE%
  exit /b %BUILD_EXIT_CODE%
)

call "%RUN_UAT%" BuildCookRun ^
  -project="%PROJECT_FILE%" ^
  -noP4 ^
  -server ^
  -serverplatform=Linux ^
  -serverconfig=Development ^
  -noclient ^
  -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 Dedicated server package failed with exit code %PACKAGE_EXIT_CODE%.
  echo Log file: %LOG_FILE%
  exit /b %PACKAGE_EXIT_CODE%
)

echo.
echo Linux dedicated server package completed successfully.
echo Archive: %ARCHIVE_DIR%
echo.
exit /b 0
