# SPDX-License-Identifier: GPL-3.0-or-later
cmake_minimum_required(VERSION 3.16)
project(realmrun C)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)

option(REALMRUN_SANITIZE "Build with ASan/UBSan" OFF)

# Headers only: never import a pkg-config link target or link a libav library.
# Cross builds deliberately use the stub rather than host headers/libraries.
option(REALMRUN_HAVE_LIBAV_HEADERS "Enable optional runtime libav backend when headers exist" ON)
set(REALMRUN_LIBAV_INCLUDE_DIR "" CACHE PATH "Directory containing libavformat, libavcodec and libavutil headers")
set(REALMRUN_MOVIE_LIBAV OFF)
if(REALMRUN_HAVE_LIBAV_HEADERS AND NOT CMAKE_CROSSCOMPILING)
    find_package(PkgConfig QUIET)
    if(PkgConfig_FOUND AND NOT REALMRUN_LIBAV_INCLUDE_DIR)
        pkg_check_modules(MOVIE_LIBAV QUIET libavformat libavcodec libavutil)
    endif()
    if(REALMRUN_LIBAV_INCLUDE_DIR)
        set(REALMRUN_LIBAV_HEADER_PATH ${REALMRUN_LIBAV_INCLUDE_DIR})
    else()
        find_path(REALMRUN_LIBAV_HEADER_PATH libavformat/avformat.h
            HINTS ${MOVIE_LIBAV_INCLUDE_DIRS})
    endif()
    if(REALMRUN_LIBAV_HEADER_PATH)
        include(CheckCSourceCompiles)
        set(CMAKE_REQUIRED_INCLUDES ${REALMRUN_LIBAV_HEADER_PATH} ${MOVIE_LIBAV_INCLUDE_DIRS})
        check_c_source_compiles("#include <libavformat/avformat.h>
            #include <libavcodec/avcodec.h>
            #include <libavutil/version.h>
            int main(void) { AVChannelLayout layout = {0}; return layout.nb_channels; }"
            REALMRUN_LIBAV_HEADERS_WORK)
        unset(CMAKE_REQUIRED_INCLUDES)
        if(REALMRUN_LIBAV_HEADERS_WORK)
            set(REALMRUN_MOVIE_LIBAV ON)
        endif()
    endif()
endif()
message(STATUS "Movie runtime libav backend: ${REALMRUN_MOVIE_LIBAV} (no libav link dependency)")

# Optional Cortex-A35 tuning for the D-019 reference board (Khadas VIM1S).
# OFF by default so the generic aarch64 (and every other) build stays portable;
# only turn on when building specifically for an A35-class SoC. Applied to all
# realmrun targets via realmrun_apply_tune() below.
option(REALMRUN_TUNE_A35 "Tune for ARM Cortex-A35 (-mcpu=cortex-a35)" OFF)

# Applies -mcpu=cortex-a35 to `target` when REALMRUN_TUNE_A35 is on and the
# compiler accepts it. No-op on non-ARM hosts / compilers that reject the flag.
function(realmrun_apply_tune target)
    if(REALMRUN_TUNE_A35)
        target_compile_options(${target} PRIVATE
            $<$<COMPILE_LANGUAGE:C>:-mcpu=cortex-a35>)
    endif()
endfunction()

# Applies the REALMRUN_SANITIZE flags to `target` directly. realmrun_core's
# own PUBLIC flags only reach targets that link it - src/main.c (the
# `realmrun` exe) does not, so every shipped binary must opt in explicitly.
function(realmrun_apply_sanitize target)
    if(REALMRUN_SANITIZE)
        target_compile_options(${target} PRIVATE -fsanitize=address,undefined -fno-omit-frame-pointer -g)
        target_link_options(${target} PRIVATE -fsanitize=address,undefined)
        add_test(NAME sanitize_${target}
                 COMMAND ${CMAKE_COMMAND} "-DBIN=$<TARGET_FILE:${target}>"
                         -P "${CMAKE_SOURCE_DIR}/cmake/check_sanitized.cmake")
    endif()
endfunction()

enable_testing()

# SDL2 is optional: the core library, its tests and the manifest-check CLI
# build without it. Only the realmrun exe and the realmrun-view tool need it.
find_package(SDL2)

# SDL2_ttf is OPTIONAL and independent of SDL2: the T-M3-04a font layer's
# TrueType backend (src/platform/font_sdl_ttf.*) is built only when it is found
# (the Linux CI box has none, the owner's Mac does). The pure-C fixed-cell
# fallback (src/ui/font.c) covers CI / headless and every automated test, so a
# missing SDL2_ttf never fails the build. Detected via pkg-config (the SDL2
# ecosystem ships an SDL2_ttf.pc); skipped when cross-compiling.
set(REALMRUN_HAVE_SDL2_TTF OFF)
if(SDL2_FOUND AND NOT CMAKE_CROSSCOMPILING)
    find_package(PkgConfig QUIET)
    if(PkgConfig_FOUND)
        pkg_check_modules(SDL2_TTF QUIET IMPORTED_TARGET SDL2_ttf)
        if(SDL2_TTF_FOUND)
            set(REALMRUN_HAVE_SDL2_TTF ON)
        endif()
    endif()
endif()
if(REALMRUN_HAVE_SDL2_TTF)
    message(STATUS "SDL2_ttf ${SDL2_TTF_VERSION} found: TrueType font backend enabled")
else()
    message(STATUS "SDL2_ttf not found: TrueType font backend disabled (fixed-cell fallback only)")
endif()

# OGG music decode (T-M2-04) is OPTIONAL: the system libvorbisfile is linked
# dynamically when present (DECISIONS D-020 proposed), otherwise src/core/music.c
# compiles to graceful stubs - music is disabled and skipped, sfx still work.
# Skipped entirely when cross-compiling so an accidental *host* libvorbis is
# never linked into the aarch64 build (D-019 proxy: music just compiles out).
# VORBISENC (encoder) is only needed to build a synthetic OGG in tests/test_music.c.
if(NOT CMAKE_CROSSCOMPILING)
    find_package(PkgConfig QUIET)
    if(PkgConfig_FOUND)
        pkg_check_modules(VORBISFILE IMPORTED_TARGET vorbisfile)
        pkg_check_modules(VORBISENC IMPORTED_TARGET vorbisenc vorbis ogg)
    endif()
endif()
if(VORBISFILE_FOUND)
    message(STATUS "libvorbisfile ${VORBISFILE_VERSION} found: OGG music enabled")
else()
    message(STATUS "libvorbisfile not found: OGG music disabled (sfx still work)")
endif()

add_subdirectory(src/core)
add_subdirectory(src/ui)
add_subdirectory(tools)
add_subdirectory(tests)

if(SDL2_FOUND)
    # Optional SDL2 glue: controller (T-M2-03) + audio device (T-M2-04) +
    # probe (T-M2-06) SDL halves, the only code that touches SDL. Pure-C11
    # src/core builds and tests without it; this only builds with SDL2.
    add_library(realmrun_platform_sdl STATIC
        src/platform/sdl_controller.c
        src/platform/sdl_mapper.c
        src/platform/sdl_audio.c
        src/platform/probe_sdl.c)
    target_link_libraries(realmrun_platform_sdl PUBLIC realmrun_core SDL2::SDL2)
    target_include_directories(realmrun_platform_sdl PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src)
    target_compile_options(realmrun_platform_sdl PRIVATE -Wall -Wextra -Werror)
    realmrun_apply_sanitize(realmrun_platform_sdl)

    add_subdirectory(src/platform)
    add_executable(realmrun src/main.c)
    target_link_libraries(realmrun PRIVATE realmrun_platform realmrun_platform_sdl realmrun_ui SDL2::SDL2)
    target_compile_options(realmrun PRIVATE -Wall -Wextra)
    realmrun_apply_sanitize(realmrun)
    realmrun_apply_tune(realmrun)
    add_test(NAME version COMMAND realmrun --version)

    # Virtual-controller test harness (T-M2-10, COUCH-COOP-PLAN §8): drives SDL
    # virtual game controllers through the controller glue into the seat manager.
    # Needs SDL_JoystickAttachVirtualEx (SDL >= 2.24); when the installed SDL2 is
    # older the target is not built and the suite is considered skipped. Even when
    # built, the test returns 77 (ctest SKIP) if the virtual driver is unavailable
    # at runtime. Headless: dummy video/audio, no window.
    if(NOT SDL2_VERSION VERSION_LESS "2.24.0")
        add_executable(test_vpad tests/test_vpad.c tests/vpad_harness.c)
        target_link_libraries(test_vpad PRIVATE realmrun_platform_sdl SDL2::SDL2)
        target_include_directories(test_vpad PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
        target_compile_options(test_vpad PRIVATE -Wall -Wextra)
        realmrun_apply_sanitize(test_vpad)
        realmrun_apply_tune(test_vpad)
        add_test(NAME vpad COMMAND test_vpad)
        set_tests_properties(vpad PROPERTIES
            LABELS vpad
            SKIP_RETURN_CODE 77
            ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
    else()
        message(STATUS "SDL2 ${SDL2_VERSION} < 2.24: vpad harness (T-M2-10) not built")
    endif()
else()
    message(STATUS "SDL2 not found: realmrun and realmrun-view will not be built")
endif()

# --- Release packaging install rules (T-M7-03) ------------------------------
# Additive, used by tools/package.sh via `cmake --install`. Installs ONLY our
# own binaries and licence/credit/notice text — NEVER game data, manifests with
# private paths, assets or original files (LEGAL.md §2/§5). The SDL front-end
# (realmrun, realmrun-view) is installed only when it was actually built (SDL2
# present for this build); otherwise the archive is the core CLIs only.
# tools/package.sh keeps a matching allowlist and fails the pack if anything
# outside it — or any LEGAL §5 forbidden marker — appears in the archive.
include(GNUInstallDirs)

# Always-built, SDL-free command-line tools (tools/CMakeLists.txt).
install(TARGETS
        realmrun-manifest-check
        realmrun-records
        realmrun-rules
        realmrun-combat
        realmrun-res
        realmrun-ui
        realmrun-scn
        realmrun-campaign
        realmrun-probe
        realmrun-mapview
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})

# SDL2 front-end: only exists when SDL2 was found at configure time.
if(TARGET realmrun)
    install(TARGETS realmrun RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
if(TARGET realmrun-view)
    install(TARGETS realmrun-view RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()

# Licence, credit and third-party notices shipped at the archive root (LEGAL §2).
install(FILES
        ${CMAKE_SOURCE_DIR}/LICENSE
        ${CMAKE_SOURCE_DIR}/LICENSE-docs
        ${CMAKE_SOURCE_DIR}/README.md
        ${CMAKE_SOURCE_DIR}/THIRD-PARTY-NOTICES.txt
        ${CMAKE_SOURCE_DIR}/docs/CREDITS.md
    DESTINATION .)
