#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SDL_SOURCE="$PROJECT_ROOT/external/SDL"
BUILD_DIR="$PROJECT_ROOT/out/build/_sdl_build/linux"
PREBUILT_DIR="$PROJECT_ROOT/prebuilt/linux"
BUILD_TYPE="${1:-Release}"

build_sdl() {
    local LINK_TYPE="$1"
    local SHARED="OFF"
    local STATIC="OFF"

    if [ "$LINK_TYPE" = "dynamic" ]; then SHARED="ON"; else STATIC="ON"; fi

    local OUT_DIR="$PREBUILT_DIR/SDL3-$LINK_TYPE"
    local BUILD_OUT="$BUILD_DIR/$LINK_TYPE"

    echo ""
    echo "=== Building SDL3 ($LINK_TYPE) for Linux ==="

    cmake -S "$SDL_SOURCE" -B "$BUILD_OUT" \
        -G "Ninja" \
        -DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
        -DCMAKE_INSTALL_PREFIX="$OUT_DIR" \
        -DCMAKE_C_COMPILER=gcc-12 \
        -DCMAKE_CXX_COMPILER=g++-12 \
        -DSDL_SHARED="$SHARED" \
        -DSDL_STATIC="$STATIC" \
        -DSDL_INSTALL=ON \
        -DSDL_TEST_LIBRARY=OFF \
        -DSDL_TESTS=OFF

    cmake --build "$BUILD_OUT"
    cmake --install "$BUILD_OUT"

    echo "=== Done: $OUT_DIR ==="
}

# Install build dependencies if needed (Debian 12 bookworm)
echo "Checking build dependencies..."
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends \
    ninja-build cmake build-essential \
    gcc-12 g++-12 \
    libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev \
    libwayland-dev libpulse-dev libasound2-dev \
    libgl1-mesa-dev

build_sdl "dynamic"
build_sdl "static"