
include_directories(${ZLIB_INCLUDE_DIRS})

# On Windows, compile the app icon into the executable so Explorer shows it on
# kat5200.exe (and the title bar/taskbar use it).  windres (MinGW) / rc (MSVC)
# embeds resources/kat5200.ico via the minimal resources/kat5200_win.rc; the
# resources/ dir is added to the include path below so the .rc resolves the
# .ico by name.
if (WIN32)
    enable_language(RC)
    set(_kat_win_rc ${CMAKE_SOURCE_DIR}/resources/kat5200.rc)
endif()

# On Android the app is loaded by SDLActivity as a shared library (libkat5200.so),
# not run as an executable.  MainActivity.getLibraries() lists "kat5200" last so
# SDL's bootstrap calls our SDL_main (see android-project/).
if(ANDROID)
    add_library(kat5200 SHARED kat5200.c kat5200.h)
else()
    add_executable(kat5200 kat5200.c kat5200.h ${_kat_win_rc})
endif()

if (WIN32)
    target_include_directories(kat5200 PRIVATE ${CMAKE_SOURCE_DIR}/resources)
endif()

# Core/minizip first (interface links them), then interface, then the GUI
# sources which compile straight into the binary (tests stub the GUI out).
add_subdirectory(core)
add_subdirectory(minizip)
add_subdirectory(interface)
add_subdirectory(gui)

if (WIN32 AND MSVC)
    add_subdirectory(win32)
endif()

# kat_interface PUBLIC-propagates kat_core, kat_minizip, SDL3, zlib,
# CURL and the KAT_DATADIR define, so this single link line covers the binary.
target_link_libraries(kat5200 kat_interface)

# macOS .app bundle.  No Xcode project is required: this produces a runnable
# kat5200.app entirely from CMake (open build/src/kat5200.app, or generate an
# IDE project on demand with `cmake -G Xcode`).  The bundle's Contents/Resources
# holds the same seed config/profiles the Linux/Windows builds ship; util.c
# (the __APPLE__ path) reads them back via CFBundle and copies them into
# ~/Library/Application Support/kat5200 on first run.
#
# The default build links SDL3 from Homebrew (fine for local dev).  For a
# self-contained, relocatable, ad-hoc-signed bundle + .dmg, run the
# kat5200-macos-dmg target (see below / cmake/package_macos_bundle.cmake).
# Apple Developer ID signing + notarization is the remaining manual step before
# distributing outside your own machine.
if (APPLE)
    # The Info.plist template's ${MACOSX_DEPLOYMENT_TARGET} feeds
    # LSMinimumSystemVersion; CMake doesn't auto-populate it from
    # CMAKE_OSX_DEPLOYMENT_TARGET for a custom plist, so mirror it here.
    set(MACOSX_DEPLOYMENT_TARGET "${CMAKE_OSX_DEPLOYMENT_TARGET}")

    set_target_properties(kat5200 PROPERTIES
        MACOSX_BUNDLE TRUE
        MACOSX_BUNDLE_INFO_PLIST       "${CMAKE_SOURCE_DIR}/resources/macos/Info.plist.in"
        MACOSX_BUNDLE_BUNDLE_NAME      "kat5200"
        MACOSX_BUNDLE_GUI_IDENTIFIER   "io.github.madjacket.kat5200"
        MACOSX_BUNDLE_BUNDLE_VERSION   "${PROJECT_VERSION}"
        MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}"
        MACOSX_BUNDLE_INFO_STRING      "kat5200 ${PROJECT_VERSION}"
        MACOSX_BUNDLE_COPYRIGHT        "Copyright (c) Brian Berlin. GPL-2.0-or-later."
        MACOSX_BUNDLE_ICON_FILE        "kat5200.icns")

    # Generate the .icns from resources/kat5200.png (see cmake/make_icns.cmake).
    set(_kat_icns "${CMAKE_CURRENT_BINARY_DIR}/kat5200.icns")
    add_custom_command(OUTPUT ${_kat_icns}
        COMMAND ${CMAKE_COMMAND}
                -D SRC_PNG=${CMAKE_SOURCE_DIR}/resources/kat5200.png
                -D OUT_ICNS=${_kat_icns}
                -P ${CMAKE_SOURCE_DIR}/cmake/make_icns.cmake
        DEPENDS ${CMAKE_SOURCE_DIR}/resources/kat5200.png
                ${CMAKE_SOURCE_DIR}/cmake/make_icns.cmake
        COMMENT "Generating kat5200.icns"
        VERBATIM)
    add_custom_target(kat5200-icns DEPENDS ${_kat_icns})
    add_dependencies(kat5200 kat5200-icns)

    # Stage the icon + runtime seed data into Contents/Resources.  Mirrors the
    # Windows `defaults/` staging above; util.c's __APPLE__ path expects exactly
    # these names (kat5200.conf, kat5200.bmp, profiles.zip, shaders/).  No
    # portable.txt: macOS has no portable mode -- the .app is already the
    # relocatable unit and live data lives in ~/Library/Application Support.
    set(_kat_res "$<TARGET_BUNDLE_DIR:kat5200>/Contents/Resources")
    add_custom_command(TARGET kat5200 POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory "${_kat_res}"
        COMMAND ${CMAKE_COMMAND} -E remove_directory
                "$<TARGET_BUNDLE_DIR:kat5200>/Contents/MacOS/shaders"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${_kat_icns}" "${_kat_res}/kat5200.icns"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_SOURCE_DIR}/resources/kat5200.conf" "${_kat_res}/kat5200.conf"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_SOURCE_DIR}/resources/kat5200.bmp" "${_kat_res}/kat5200.bmp"
        COMMAND ${CMAKE_COMMAND}
                -D BUNDLE_MANIFEST=${KAT_SHADER_BUNDLE_MANIFEST}
                -D SOURCE_ROOT=${KAT_SHADER_BUNDLE_SOURCE_ROOT}
                -D "DEST_ROOT=${_kat_res}/shaders"
                -P ${CMAKE_SOURCE_DIR}/cmake/stage_shader_bundles.cmake
        # Drop any loose profile trees left by an older build before this switch
        # to a packed profiles.zip, so they are not double-staged into the .app.
        COMMAND ${CMAKE_COMMAND} -E rm -rf
                "${_kat_res}/profiles.5200" "${_kat_res}/profiles.8bit"
        COMMAND ${CMAKE_COMMAND}
                -D "PROFILES_SRC=${CMAKE_SOURCE_DIR}/src/sql/dats"
                -D "OUTPUT_ZIP=${_kat_res}/profiles.zip"
                -P ${CMAKE_SOURCE_DIR}/cmake/make_profiles_zip.cmake
        COMMAND ${CMAKE_COMMAND}
                -D "MANUAL_PDF=${KAT_PACKAGE_MANUAL_PDF}"
                -D "MANUAL_PDF_NAME=${KAT_MANUAL_PDF_NAME}"
                -D "DEST_DIR=${_kat_res}"
                -D REQUIRE_MANUAL=0
                -P ${CMAKE_SOURCE_DIR}/cmake/stage_manual.cmake
        COMMENT "Staging seed resources into kat5200.app"
        VERBATIM)

    # Developer-convenience target (NOT part of `all`): turn the Homebrew-linked
    # dev .app into a relocatable, ad-hoc-signed bundle + compressed .dmg under
    # build/dist.  See cmake/package_macos_bundle.cmake.  Run explicitly:
    #   cmake --build build --target kat5200-macos-dmg
    add_custom_target(kat5200-macos-dmg
        COMMAND ${CMAKE_COMMAND}
                -D APP_BUNDLE=$<TARGET_BUNDLE_DIR:kat5200>
                -D STAGE_DIR=${CMAKE_BINARY_DIR}/dist
                -D VERSION=${PROJECT_VERSION}
                -D "MANUAL_PDF=${KAT_PACKAGE_MANUAL_PDF}"
                -D "MANUAL_PDF_NAME=${KAT_MANUAL_PDF_NAME}"
                -D "STAGE_MANUAL_SCRIPT=${CMAKE_SOURCE_DIR}/cmake/stage_manual.cmake"
                -P ${CMAKE_SOURCE_DIR}/cmake/package_macos_bundle.cmake
        DEPENDS kat5200
        VERBATIM
        COMMENT "Building relocatable kat5200.app + .dmg")
endif()

# Windows runtime layout: the app reads its pristine config + profiles from a
# <exe-dir>\defaults directory and loads the window icon from a bitmap beside
# the exe.  Stage the seed tree into the build output so a fresh build can run
# without a manual copy.  The Inno Setup installer mirrors this.
if (WIN32)
    set(_kat_defaults "$<TARGET_FILE_DIR:kat5200>/defaults")
    add_custom_command(TARGET kat5200 POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory "${_kat_defaults}"
        COMMAND ${CMAKE_COMMAND} -E remove_directory
                "$<TARGET_FILE_DIR:kat5200>/shaders"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_SOURCE_DIR}/resources/kat5200.conf" "${_kat_defaults}/kat5200.conf"
        COMMAND ${CMAKE_COMMAND}
                -D BUNDLE_MANIFEST=${KAT_SHADER_BUNDLE_MANIFEST}
                -D SOURCE_ROOT=${KAT_SHADER_BUNDLE_SOURCE_ROOT}
                -D "DEST_ROOT=${_kat_defaults}/shaders"
                -P ${CMAKE_SOURCE_DIR}/cmake/stage_shader_bundles.cmake
        # Drop any loose profile trees left by an older build before this switch
        # to a packed profiles.zip, so they are not double-staged beside the exe.
        COMMAND ${CMAKE_COMMAND} -E rm -rf
                "${_kat_defaults}/profiles.5200" "${_kat_defaults}/profiles.8bit"
        COMMAND ${CMAKE_COMMAND}
                -D "PROFILES_SRC=${CMAKE_SOURCE_DIR}/src/sql/dats"
                -D "OUTPUT_ZIP=${_kat_defaults}/profiles.zip"
                -P ${CMAKE_SOURCE_DIR}/cmake/make_profiles_zip.cmake
        COMMAND ${CMAKE_COMMAND}
                -D "MANUAL_PDF=${KAT_PACKAGE_MANUAL_PDF}"
                -D "MANUAL_PDF_NAME=${KAT_MANUAL_PDF_NAME}"
                -D "DEST_DIR=${_kat_defaults}"
                -D REQUIRE_MANUAL=0
                -P ${CMAKE_SOURCE_DIR}/cmake/stage_manual.cmake
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_SOURCE_DIR}/resources/kat5200.bmp" "$<TARGET_FILE_DIR:kat5200>/kat5200.bmp"
        VERBATIM)
endif()

# Portable package: bundle the staged runtime + auto-discovered MinGW DLLs into
# a self-contained folder and zip.  MinGW/MSYS only (uses objdump + the UCRT64
# toolchain DLLs); not built by default -- invoke the explicit target.
if (WIN32 AND MINGW)
    get_filename_component(_kat_toolchain_bin "${CMAKE_C_COMPILER}" DIRECTORY)
    add_custom_target(kat5200-portable-package
        COMMAND ${CMAKE_COMMAND}
                -D PACKAGE_VERSION=${PROJECT_VERSION}
                -D SOURCE_RUNTIME_DIR=$<TARGET_FILE_DIR:kat5200>
                -D PACKAGE_ROOT=${CMAKE_BINARY_DIR}/dist/kat5200-${PROJECT_VERSION}-win64-portable
                -D TOOLCHAIN_BIN=${_kat_toolchain_bin}
                -D OBJDUMP=${CMAKE_OBJDUMP}
                -D "MANUAL_PDF=${KAT_PACKAGE_MANUAL_PDF}"
                -D "MANUAL_PDF_NAME=${KAT_MANUAL_PDF_NAME}"
                -D "STAGE_MANUAL_SCRIPT=${CMAKE_SOURCE_DIR}/cmake/stage_manual.cmake"
                -P ${CMAKE_SOURCE_DIR}/cmake/package_msys_portable.cmake
        DEPENDS kat5200
        VERBATIM
        COMMENT "Building portable kat5200 package")
endif()

# Install rules: Linux/FHS-style only.  macOS uses an .app bundle, Windows
# uses an installer (kat5200.iss), and Android packs assets into the APK,
# so none of these targets apply there.
if (UNIX AND NOT APPLE AND NOT ANDROID)
    install(TARGETS kat5200 RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})

    # Seed config + bitmap consumed on first run.
    install(FILES
            ${CMAKE_SOURCE_DIR}/resources/kat5200.conf
            ${CMAKE_SOURCE_DIR}/resources/kat5200.bmp
        DESTINATION ${KAT_DATADIR})

    install(FILES
            ${CMAKE_SOURCE_DIR}/resources/shaders/bundles/README.md
        DESTINATION ${KAT_DATADIR}/shaders/bundles)
    foreach(_kat_old_shader_bundle IN LISTS KAT_NON_DISTRIBUTED_SHADER_BUNDLES)
        install(CODE
            "file(REMOVE_RECURSE \"\$ENV{DESTDIR}${KAT_DATADIR}/shaders/bundles/${_kat_old_shader_bundle}\")")
    endforeach()
    install(DIRECTORY
            ${KAT_DISTRIBUTED_SHADER_BUNDLE_DIRS}
        DESTINATION ${KAT_DATADIR}/shaders/bundles)

    # Default machine/controller profiles, packed into a single archive that is
    # extracted on first run (util_unzip_to_directory) instead of installing
    # ~14k loose files -- see cmake/make_profiles_zip.cmake.
    install(CODE "execute_process(
        COMMAND \"${CMAKE_COMMAND}\"
                -D \"PROFILES_SRC=${CMAKE_SOURCE_DIR}/src/sql/dats\"
                -D \"OUTPUT_ZIP=\$ENV{DESTDIR}${KAT_DATADIR}/profiles.zip\"
                -P \"${CMAKE_SOURCE_DIR}/cmake/make_profiles_zip.cmake\"
        RESULT_VARIABLE _kat_zip_rc)
if(NOT _kat_zip_rc EQUAL 0)
    message(FATAL_ERROR \"profiles.zip install failed\")
endif()")

    install(CODE "
execute_process(
    COMMAND \"${CMAKE_COMMAND}\"
            -D \"MANUAL_PDF=${KAT_PACKAGE_MANUAL_PDF}\"
            -D \"MANUAL_PDF_NAME=${KAT_MANUAL_PDF_NAME}\"
            -D \"DEST_DIR=\$ENV{DESTDIR}${KAT_DATADIR}\"
            -D REQUIRE_MANUAL=0
            -P \"${CMAKE_SOURCE_DIR}/cmake/stage_manual.cmake\"
    RESULT_VARIABLE _kat_manual_rc)
if(NOT _kat_manual_rc EQUAL 0)
    message(FATAL_ERROR \"manual PDF install failed\")
endif()")

    # Desktop integration.  Install the icon at every hicolor size we ship a
    # correctly-sized PNG for (resources/icon/hicolor/<n>x<n>.png, produced by
    # resources/icon/make_icons.py) so launchers/menus pick a crisp size rather
    # than scaling one mismatched bitmap.
    foreach(_kat_icon_sz 48 64 128 256)
        install(FILES ${CMAKE_SOURCE_DIR}/resources/icon/hicolor/${_kat_icon_sz}x${_kat_icon_sz}.png
            DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/${_kat_icon_sz}x${_kat_icon_sz}/apps
            RENAME io.github.madjacket.kat5200.png)
    endforeach()
    install(FILES ${CMAKE_SOURCE_DIR}/resources/io.github.madjacket.kat5200.desktop
        DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
    install(FILES ${CMAKE_SOURCE_DIR}/resources/io.github.madjacket.kat5200.metainfo.xml
        DESTINATION ${CMAKE_INSTALL_DATADIR}/metainfo)
endif()
