add_subdirectory(3DEXT)

# Windows resource file: icon + VERSIONINFO. Generated under
# ${CMAKE_BINARY_DIR}/packaging/ by configure_file in the root CMakeLists.txt.
if(WIN32)
    enable_language(RC)
endif()

set(EMBEDDED_LBA2_CFG_CPP ${CMAKE_BINARY_DIR}/SOURCES/embedded_lba2_cfg_data.cpp)
add_custom_command(
    OUTPUT ${EMBEDDED_LBA2_CFG_CPP}
    COMMAND ${CMAKE_COMMAND} "-DINPUT=${CMAKE_SOURCE_DIR}/SOURCES/LBA2.CFG"
            "-DOUTPUT=${EMBEDDED_LBA2_CFG_CPP}" -P
            ${CMAKE_SOURCE_DIR}/cmake/embed_lba2_cfg.cmake
    DEPENDS ${CMAKE_SOURCE_DIR}/SOURCES/LBA2.CFG ${CMAKE_SOURCE_DIR}/cmake/embed_lba2_cfg.cmake
    COMMENT "Embedding SOURCES/LBA2.CFG for default config fallback"
)

# General sources
set(SOURCES_FILES AMBIANCE.CPP BOOT_EXIT.CPP DISTRIB.CPP AUDIO_BALANCE.CPP AUDIO_CONSOLE.CPP ANIMTEX.CPP BEZIER.CPP BUILD_INFO.CPP BUGGY.CPP CHEATCOD.CPP CLI_ARGS.CPP COMPORTE.CPP CONFIG.CPP CONTROL.CPP CONTROL_PROTO.CPP CONTROL_SERVER.CPP CREDITS.CPP CREDITS_PARSE.CPP
        CONFIG_FILE.CPP DART.CPP DEMO_SEED.CPP DIRECTORIES.CPP DISKFUNC.CPP EMBEDDED_CFG_WRITE.CPP EXIT_SCREEN.CPP EXTFUNC.CPP EXTRA.CPP FICHE.CPP FLOW.CPP FOLLOWCAM.CPP GAMEMENU.CPP GAMEMENU_MOUSE.CPP MOUSE_CAPTURE.CPP MENU_INPUT.CPP MENU_KEYNAV.CPP MENU_LABELS.CPP GERELIFE.CPP
        GERETRAK.CPP GLOBAL.CPP GRILLE.CPP HOLOBODY.CPP HOLOGLOB.CPP HOLOPLAN.CPP IMPACT.CPP INCRUST.CPP INITADEL.C
        INPUT.CPP INPUT_BINDINGS.CPP INTEXT.CPP INVENT.CPP JOYSTICK.CPP LZSS.CPP MEM.CPP MESSAGE.CPP MUSIC.CPP OBJECT.CPP PATCH.CPP IMAGE_LOAD.CPP PERFTRACE.CPP PERSO.CPP
        RES_CATALOG.CPP RES_DISCOVERY.CPP RES_MENU.CPP RES_PICKER.CPP RES_SWITCH.CPP RETAILFIX.CPP
        PLAYACF.CPP POF.CPP RAIN.CPP RECORD.CPP RECORD_FORMAT.CPP SETTINGS.CPP SAVEGAME.CPP SAVEGAME_WIRE.CPP SAVEGAME_LOAD_BOUNDS.CPP SAVENAME_VALIDATION.CPP SCAN.CPP SORT.CPP TOUCH_INPUT.CPP VALIDPOS.CPP VERSION.CPP WAGON.CPP ZV.CPP)
# set(SOURCES_FILES_ASM COMPRESS.ASM FIRE.ASM FLOW_A.ASM FUNC.ASM GRILLE_A.ASM PLASMA.ASM)
#set(SOURCES_FILES_ASM_EXCLUDED COPY.ASM)
set(SOURCES_FILES_ASM COMPRESS.CPP FIRE.CPP FLOW_A.CPP FUNC.CPP GRILLE_A.CPP PLASMA.CPP)

# Windows specific sources (JOYSTICK.CPP moved to general sources — SDL3 gamepad API is portable)
set(SOURCES_FILES_WIN)

# DOS specific sources
set(SOURCES_FILES_DOS CRITICAL.CPP HERCULE.CPP)
set(SOURCES_FILES_ASM_DOS DEC_XCF.ASM HERCUL_A.ASM KEYB.ASM)

list(APPEND SOURCES_FILES CONSOLE/CONSOLE_CMD.CPP)
list(APPEND SOURCES_FILES ASSET_PREFLIGHT.CPP)
if(WIN32)
    list(APPEND SOURCES_FILES_WIN ${CMAKE_BINARY_DIR}/packaging/lba2cc.rc)
endif()

# On macOS, the .icns icon goes inside the .app's Contents/Resources/ via
# the MACOSX_PACKAGE_LOCATION property below. Adding it to the source list
# makes CMake aware of the dependency so the .app rebuilds when the icon
# is regenerated.
set(SOURCES_FILES_MACOS "")
if(APPLE)
    list(APPEND SOURCES_FILES_MACOS
         ${CMAKE_BINARY_DIR}/packaging/${LBA2_DESKTOP_ID}.icns)
endif()

# On Android the game is built as a shared library (.so) loaded by SDL3's Java
# Activity wrapper. On all other platforms it is a standalone executable.
# LBA2_ANDROID_EXECUTABLE takes the executable branch on Android too, for the
# on-device automation lane, which needs argv and an exit code the Activity
# cannot give it.
if(ANDROID AND NOT LBA2_ANDROID_EXECUTABLE)
    add_library(${LBA2_EXECUTABLE_NAME} SHARED ${SOURCES_FILES} ${SOURCES_FILES_ASM} ${SOURCES_FILES_WIN} ${SOURCES_FILES_MACOS} ${EMBEDDED_LBA2_CFG_CPP})
    # The APK ships the library as libmain.so, the name SDL's activity loads, and a
    # tombstone names a library by its SONAME. Matching them lets a tombstone and
    # the engine's crash block name the same module.
    set_target_properties(${LBA2_EXECUTABLE_NAME} PROPERTIES NO_SONAME ON)
    target_link_options(${LBA2_EXECUTABLE_NAME} PRIVATE -Wl,-soname,libmain.so)
else()
    add_executable(${LBA2_EXECUTABLE_NAME} ${SOURCES_FILES} ${SOURCES_FILES_ASM} ${SOURCES_FILES_WIN} ${SOURCES_FILES_MACOS} ${EMBEDDED_LBA2_CFG_CPP})
endif()
target_sources(${LBA2_EXECUTABLE_NAME} PRIVATE $<TARGET_OBJECTS:lba2_platform_entry>)
if(LBA2_GAMEPAD_STICK_LAYOUT)
    target_compile_definitions(${LBA2_EXECUTABLE_NAME} PRIVATE LBA2_GAMEPAD_STICK_LAYOUT=1)
endif()

# macOS .app bundle metadata: marks the target as a bundled .app, points
# at the configured Info.plist, and routes the .icns to Contents/Resources/.
# Without MACOSX_BUNDLE the binary would be a bare executable in
# build/SOURCES/, not a launchable .app.
#
# OUTPUT_NAME drives both the bundle directory name (<OUTPUT_NAME>.app) and
# the inner Mach-O filename. We want them to diverge: the bundle is the
# user-facing display name ("LBA2 Classic Community.app" — what Finder
# shows on disk), while the inner binary stays as the terse executable
# name ("lba2cc" — what CLI users invoke and what CFBundleExecutable points
# at). CMake has no single property that splits these, so we set
# OUTPUT_NAME to the product name and rename the inner binary back to
# LBA2_EXECUTABLE_NAME with a POST_BUILD step (ordered before codesign so
# the signature covers the final layout).
if(APPLE)
    set_target_properties(${LBA2_EXECUTABLE_NAME} PROPERTIES
        MACOSX_BUNDLE TRUE
        MACOSX_BUNDLE_INFO_PLIST ${CMAKE_BINARY_DIR}/packaging/Info.plist
        OUTPUT_NAME ${LBA2_PRODUCT_NAME})
    set_source_files_properties(
        ${CMAKE_BINARY_DIR}/packaging/${LBA2_DESKTOP_ID}.icns
        PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
    add_dependencies(${LBA2_EXECUTABLE_NAME} lba2_icns)

    # Rename Contents/MacOS/<product-name> → Contents/MacOS/<exe-name>.
    # CFBundleExecutable in Info.plist already points at LBA2_EXECUTABLE_NAME,
    # so after the rename macOS launches the renamed file correctly.
    add_custom_command(TARGET ${LBA2_EXECUTABLE_NAME} POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E rename
                $<TARGET_FILE:${LBA2_EXECUTABLE_NAME}>
                $<TARGET_BUNDLE_CONTENT_DIR:${LBA2_EXECUTABLE_NAME}>/MacOS/${LBA2_EXECUTABLE_NAME}
        COMMENT "Renaming inner binary to ${LBA2_EXECUTABLE_NAME}"
        VERBATIM)

    # Ad-hoc codesign the .app post-build. Apple Silicon (macOS 11+) refuses
    # to launch unsigned binaries — Gatekeeper reports the app as "damaged"
    # and offers only "Move to Bin" as a remedy, even though the binary is
    # fine. The `-` identity is an ad-hoc self-attestation (no Apple
    # Developer account required); it gets the .app past the on-load
    # signature check while we wait for real Developer ID + notarization
    # to land. --deep covers any nested frameworks (none today, but
    # future-proof for when SDL3 might ship as a bundled .dylib).
    add_custom_command(TARGET ${LBA2_EXECUTABLE_NAME} POST_BUILD
        COMMAND codesign --force --deep --sign -
                $<TARGET_BUNDLE_DIR:${LBA2_EXECUTABLE_NAME}>
        COMMENT "Ad-hoc codesigning ${LBA2_PRODUCT_NAME}.app"
        VERBATIM)

    # A Mach-O binary carries no DWARF: dsymutil collects it from the object files
    # the link read. With LTO those are temporaries the linker deletes, and the dSYM
    # comes out empty unless the linker is told to keep them.
    if(LBA2_RELEASE_SYMBOLS)
        target_link_options(${LBA2_EXECUTABLE_NAME} PRIVATE
            "-Wl,-object_path_lto,${CMAKE_CURRENT_BINARY_DIR}/${LBA2_EXECUTABLE_NAME}-lto")
    endif()
endif()
# GCC LTO mis-infers T_PLASMA::data_start size when ptrc writes into Malloc tail (see ANIMTEX.CPP plasma case).
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
  set_source_files_properties(ANIMTEX.CPP PROPERTIES COMPILE_OPTIONS "-Wno-stringop-overflow")
  target_link_options(${LBA2_EXECUTABLE_NAME} PRIVATE "-Wno-stringop-overflow")
endif()
add_subdirectory(CONSOLE)
target_link_libraries(${LBA2_EXECUTABLE_NAME} PRIVATE console)
target_include_directories(${LBA2_EXECUTABLE_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/CONSOLE)
# Explicit order matters for GNU static linking: poly references RoundType/ROUND in libsys (UTILS.CPP);
# sys must follow poly. (Transitive deps from 3dext alone order sys before poly and break -m32 links.)
target_link_libraries(${LBA2_EXECUTABLE_NAME} PRIVATE 3dext 3D ail ani fio obj poly svg sys lba2_platform)
# A UWP build (LBA2_WINDOWS_APP, set by cmake/llvm-mingw-x86_64-uwp.cmake) takes its
# imports from the toolchain's windowsapp library instead of the desktop DLLs.
if (WIN32 AND NOT LBA2_WINDOWS_APP)
    target_link_libraries(${LBA2_EXECUTABLE_NAME} PRIVATE gdi32 user32 ddraw winmm kernel32)
    if (LBA2_CONTROL_SERVER)
        # Winsock, for --listen. Only linked when the socket is compiled in, so a
        # normal Windows build keeps exactly the dependencies it had.
        target_link_libraries(${LBA2_EXECUTABLE_NAME} PRIVATE ws2_32)
    endif()
    if(LBA2_LINK_STATIC AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
        # Fold the GCC C++ runtime into the binary so the released .exe has
        # no MSYS2/MinGW DLL dependencies (libstdc++-6.dll, libgcc_s_seh-1.dll,
        # libwinpthread-1.dll). Combined with -DLBA2_LINK_STATIC=ON also
        # statically linking SDL3, the result is a single self-contained .exe.
        target_link_options(${LBA2_EXECUTABLE_NAME} PRIVATE
            -static-libstdc++ -static-libgcc -static)
    endif()
elseif (LBA2_WINDOWS_APP)
    # libc++ and libunwind go into the .exe, so the app folder needs no DLLs.
    # UWP/ENTRY.CPP's wWinMain, and no console window. --wrap=exit: it records
    # a scripted run's exit code (tools/uwp/xbox-lba2cc.py). Only this
    # executable has the entry, so tests and tools linking lba2_platform do not
    # take these.
    target_link_options(${LBA2_EXECUTABLE_NAME} PRIVATE -static -municode -mwindows -Wl,--wrap=exit)
endif ()

# Optional: polygon recording support for ASM-vs-CPP testing
# (option declared in top-level CMakeLists.txt)
if(ENABLE_POLY_RECORDING)
  target_link_libraries(${LBA2_EXECUTABLE_NAME} PRIVATE snapshot)
  target_compile_definitions(${LBA2_EXECUTABLE_NAME} PRIVATE ENABLE_POLY_RECORDING)
endif()

# Ensure VERSION_GENERATED.h is up-to-date before any TU including
# BUILD_INFO.h is compiled. The lba2_version_gen target is declared in
# cmake/git_version.cmake and runs the write_version.cmake script.
add_dependencies(${LBA2_EXECUTABLE_NAME} lba2_version_gen)

# Put libsmacker before LIB386/H so <smacker.h> resolves to libsmacker on case-insensitive FS (e.g. macOS)
target_include_directories(${LBA2_EXECUTABLE_NAME} PRIVATE
        ${CMAKE_BINARY_DIR}
        $<$<STREQUAL:${MVIDEO_BACKEND},smacker>:${CMAKE_SOURCE_DIR}/LIB386/libsmacker>
        ../LIB386/H)
target_compile_definitions(${LBA2_EXECUTABLE_NAME} PRIVATE ONE_GAME_DIRECTORY LBA_GAME CDROM
        $<$<STREQUAL:${MVIDEO_BACKEND},null>:USE_MVIDEO_NULL>
        $<$<STREQUAL:${MVIDEO_BACKEND},smacker>:USE_MVIDEO_SMACKER>)
if(NINTENDO_SWITCH)
    include(${CMAKE_SOURCE_DIR}/cmake/switch-package.cmake)
endif()
if(VITA)
    target_compile_definitions(${LBA2_EXECUTABLE_NAME} PRIVATE LBA2_GAMEPAD_DEADZONE_DEFAULT=13107)
    include(${CMAKE_SOURCE_DIR}/cmake/vita-package.cmake)
endif()
if(MVIDEO_BACKEND STREQUAL "smacker")
  target_sources(${LBA2_EXECUTABLE_NAME} PRIVATE VIDEO_SOURCE.CPP)
  target_link_libraries(${LBA2_EXECUTABLE_NAME} PRIVATE libsmacker video_audio_resample)
endif()

# Configure all ASM files to be recognized as such (workaround for bug where .ASM uppercase extension is not recognized)
# foreach (FILE_ASM IN LISTS SOURCES_FILES_ASM SOURCES_FILES_ASM_DOS)
#     set_source_files_properties(${FILE_ASM} PROPERTIES LANGUAGE ASM_MASM)
# endforeach ()

# Source files in folder but not used on CMakeScript:
# - DEC.ASM
# - MESSTWIN.CPP (Commented on source file "GERELIFE.CPP")
