# Resolves pre-built SDL2_mixer libraries based on PLATFORM and SDL_LINK_TYPE.
#
# Windows: prebuilt/windows/ is committed to the repository.
#          Run scripts/bootstrap_sdl_mixer_windows.ps1 once to (re)generate it.
# Linux:   prebuilt/linux/ is built in-place on the Linux remote.
#          Run scripts/bootstrap_sdl_mixer_linux.sh once after cloning.

set(SDL_MIXER_PREBUILT_DIR "${CMAKE_SOURCE_DIR}/prebuilt/${PLATFORM}")

if(SDL_LINK_TYPE STREQUAL "static")
    set(SDL_MIXER_SEARCH_DIR "${SDL_MIXER_PREBUILT_DIR}/SDL2_mixer-static")
else()
    set(SDL_MIXER_SEARCH_DIR "${SDL_MIXER_PREBUILT_DIR}/SDL2_mixer-dynamic")
endif()

message(STATUS "Looking for SDL2_mixer in: ${SDL_MIXER_SEARCH_DIR}")

find_package(SDL2_mixer REQUIRED CONFIG
    PATHS "${SDL_MIXER_SEARCH_DIR}"
    NO_DEFAULT_PATH
)

if(SDL_LINK_TYPE STREQUAL "static")
    set(SDL_MIXER_TARGET SDL2_mixer::SDL2_mixer-static)
else()
    set(SDL_MIXER_TARGET SDL2_mixer::SDL2_mixer)
endif()

message(STATUS "SDL_MIXER_TARGET resolved to: ${SDL_MIXER_TARGET}")

if(SDL_LINK_TYPE STREQUAL "dynamic" AND WIN32)
    add_custom_target(copy_sdl_mixer_dll ALL
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            $<TARGET_FILE:SDL2_mixer::SDL2_mixer>
            "${CMAKE_BINARY_DIR}/game/$<TARGET_FILE_NAME:SDL2_mixer::SDL2_mixer>"
        COMMENT "Copying SDL2_mixer.dll to output directory"
    )
endif()

if(SDL_LINK_TYPE STREQUAL "dynamic" AND UNIX AND NOT APPLE)
    get_target_property(SDL2_MIXER_SO_LOCATION SDL2_mixer::SDL2_mixer LOCATION)
    get_filename_component(SDL2_MIXER_LIB_DIR "${SDL2_MIXER_SO_LOCATION}" DIRECTORY)
    message(STATUS "SDL2_mixer runtime library directory: ${SDL2_MIXER_LIB_DIR}")
    list(APPEND SDL_LINUX_RPATH "${SDL2_MIXER_LIB_DIR}")
    set(SDL_LINUX_RPATH "${SDL_LINUX_RPATH}" CACHE INTERNAL "")
endif()