#!/usr/bin/env bash
# One-time bootstrap: builds SDL3 from source and installs it into prebuilt/linux/.
# Run this once on the Linux remote after cloning. Re-run only when upgrading SDL.
set -euo pipefail

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

# Install build dependencies (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

# Download SDL source if not already present
if [ ! -d "$SDL_SOURCE" ]; then
    echo ""
    echo "=== Downloading SDL3 $SDL_VERSION ==="
    mkdir -p "$BUILD_DIR"
    curl -L "https://github.com/libsdl-org/SDL/archive/refs/tags/release-${SDL_VERSION}.tar.gz" \
        | tar -xz -C "$BUILD_DIR"
    mv "$BUILD_DIR/SDL-release-${SDL_VERSION}" "$SDL_SOURCE"
fi

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 ==="
}

create_dynamic_symlinks() {
    local LIB_DIR="$PREBUILT_DIR/SDL3-dynamic/lib"

    local REAL_FILE
    REAL_FILE="$(find "$LIB_DIR" -maxdepth 1 -name 'libSDL3.so.*.*' | head -1)"

    if [ -z "$REAL_FILE" ]; then
        echo "ERROR: No versioned libSDL3.so file found in $LIB_DIR" >&2
        exit 1
    fi

    local REAL_NAME
    REAL_NAME="$(basename "$REAL_FILE")"
    local SONAME="${REAL_NAME%.*}"

    echo ""
    echo "=== Creating SDL3 symlinks in $LIB_DIR ==="
    echo "  $SONAME -> $REAL_NAME"
    echo "  libSDL3.so -> $SONAME"

    ln -sf "$REAL_NAME" "$LIB_DIR/$SONAME"
    ln -sf "$SONAME"    "$LIB_DIR/libSDL3.so"

    echo "=== Done ==="
}

build_sdl "dynamic"
build_sdl "static"
create_dynamic_symlinks