#!/usr/bin/env bash
# One-time bootstrap: builds SDL2_mixer from source and installs it into prebuilt/linux/.
# SDL3 must already be bootstrapped via bootstrap_sdl_linux.sh before running this.
# Run this once on the Linux remote after cloning. Re-run only when upgrading SDL2_mixer.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SDL_MIXER_VERSION="${1:-2.8.1}"
BUILD_TYPE="${2:-Release}"
BUILD_DIR="$PROJECT_ROOT/out/build/_sdl_mixer_bootstrap/linux"
PREBUILT_DIR="$PROJECT_ROOT/prebuilt/linux"
SDL_MIXER_SOURCE="$BUILD_DIR/SDL2_mixer-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 \
    libmpg123-dev libopusfile-dev libvorbis-dev libflac-dev

# Download SDL2_mixer source if not already present
if [ ! -d "$SDL_MIXER_SOURCE" ]; then
    echo ""
    echo "=== Downloading SDL2_mixer $SDL_MIXER_VERSION ==="
    mkdir -p "$BUILD_DIR"
    curl -L "https://github.com/libsdl-org/SDL_mixer/releases/download/release-${SDL_MIXER_VERSION}/SDL2_mixer-${SDL_MIXER_VERSION}.tar.gz" \
        | tar -xz -C "$BUILD_DIR"
    mv "$BUILD_DIR/SDL2_mixer-${SDL_MIXER_VERSION}" "$SDL_MIXER_SOURCE"
fi

build_sdl_mixer() {
    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/SDL2_mixer-$LINK_TYPE"
    local BUILD_OUT="$BUILD_DIR/$LINK_TYPE"

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

    # Wipe any stale build directory to avoid corrupted cache issues
    if [ -d "$BUILD_OUT" ]; then
        echo "Removing stale build directory: $BUILD_OUT"
        rm -rf "$BUILD_OUT"
    fi

    cmake -S "$SDL_MIXER_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 \
        -DSDL2MIXER_SHARED="$SHARED" \
        -DSDL2MIXER_STATIC="$STATIC" \
        -DSDL2MIXER_INSTALL=ON \
        -DSDL2MIXER_SAMPLES=OFF \
        -DSDL2MIXER_MIDI_FLUIDSYNTH=OFF \
        -DSDL2MIXER_WAVPACK=OFF \
        -DSDL3_DIR="$PREBUILT_DIR/SDL3-$LINK_TYPE/lib/cmake/SDL3"

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

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

build_sdl_mixer "dynamic"
build_sdl_mixer "static"