#!/bin/bash
set -e

echo "======================= Linux Build Script ======================="
echo "Running on OS: $OSTYPE"

# Optional: Check for a Gitea runner-specific environment variable.
if [ -z "$GITEA_RUNNER" ]; then
    echo "Warning: This script does not appear to be running in a Gitea runner environment."
fi

# Get the user's home directory
USER_HOME="$HOME"

# Detect operating system
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" || "$OSTYPE" == "win32" ]]; then
    echo "Running on Windows - cross-compiling for Linux"
    IS_WINDOWS=1
    
    # Set up Unreal Engine paths for Windows (but targeting Linux)
    UE_ROOT="E:/Games/UE_5.5"
    UE_EDITOR="$UE_ROOT/Engine/Binaries/Win64/UnrealEditor.exe"
    UE_UAT="$UE_ROOT/Engine/Build/BatchFiles/RunUAT.bat"
    
    # Set the Linux toolchain path - this is where it was installed by Chocolatey
    TOOLCHAIN_PATH="/c/UnrealToolchains/v23_clang-18.1.0-rockylinux8"
    
    if [ -d "$TOOLCHAIN_PATH" ]; then
        export LINUX_MULTIARCH_ROOT="$TOOLCHAIN_PATH"
        echo "Using Linux toolchain at: $LINUX_MULTIARCH_ROOT"
    else
        echo "ERROR: Linux toolchain not found at $TOOLCHAIN_PATH!"
        echo "Please verify the toolchain installation path."
        exit 1
    fi
else
    echo "Running on Linux - native compilation"
    IS_WINDOWS=0
    
    # Set up Unreal Engine paths for Linux
    UE_ROOT="/home/runner/UnrealEngine/UE_5.5"
    UE_EDITOR="$UE_ROOT/Engine/Binaries/Linux/UnrealEditor"
    UE_UAT="$UE_ROOT/Engine/Build/BatchFiles/RunUAT.sh"
    
    # Make sure the UAT script is executable (only needed on Linux)
    chmod +x "$UE_UAT"
fi

# Set up project paths based on the current working directory
PROJECT_ROOT="$(pwd)"
PROJECT_FILE="$PROJECT_ROOT/Luckyrobots.uproject"
ARCHIVE_DIR="$PROJECT_ROOT/Builds/Linux"

# Create the archive directory if it does not exist
mkdir -p "$ARCHIVE_DIR"

echo "Starting Linux build of Luckyrobots..."
echo "Linux toolchain path: $LINUX_MULTIARCH_ROOT"

# Run the build command using Unreal's Automation Tool (UAT)
"$UE_UAT" -ScriptsForProject="$PROJECT_FILE" Turnkey \
  -command=VerifySdk \
  -platform=Linux \
  -UpdateIfNeeded \
  -EditorIO \
  -EditorIOPort=59484 \
  -project="$PROJECT_FILE" \
  BuildCookRun \
  -nop4 \
  -utf8output \
  -cook \
  -project="$PROJECT_FILE" \
  -target=Luckyrobots \
  -unrealexe="$UE_EDITOR" \
  -platform=Linux \
  -installed \
  -stage \
  -archive \
  -package \
  -build \
  -iterativecooking \
  -pak \
  -iostore \
  -compressed \
  -prereqs \
  -archivedirectory="$ARCHIVE_DIR" \
  -CrashReporter \
  -clientconfig=Shipping
  # Uncomment the following lines if you wish to test the build without pak and iostore:
  # -skipiostore \
  # -skippak \

echo "Linux build completed. Output is in $ARCHIVE_DIR"