cmake_minimum_required(VERSION 4.0.0)
project(Echoion VERSION 1.0.0 LANGUAGES CXX)

include(GNUInstallDirs)
include(cmake/DependencyLock.cmake)

# Default to a Release build when the developer/CI did not pick a config.
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
# compiled with the same optimisation level as Echoion itself.
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
    set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
        Debug Release RelWithDebInfo MinSizeRel)
    message(STATUS "No CMAKE_BUILD_TYPE set; defaulting to Release")
endif()

# Use ccache (or sccache) as a compiler launcher when available to speed up
# incremental and clean-from-cache rebuilds. Opt-out with -DECHOION_USE_CCACHE=OFF.
option(ECHOION_USE_CCACHE "Use ccache/sccache compiler launcher if found" ON)
if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
    find_program(ECHOION_CCACHE_PROGRAM NAMES ccache sccache)
    if(ECHOION_CCACHE_PROGRAM)
        set(CMAKE_C_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
        set(CMAKE_CXX_COMPILER_LAUNCHER "${ECHOION_CCACHE_PROGRAM}")
        message(STATUS "Compiler cache enabled: ${ECHOION_CCACHE_PROGRAM}")
    endif()
endif()

# Decide linkage before configuring CPM dependencies. Protocol and VoidLibrary
# must be part of the validated echoiond artifact in production, otherwise a
# release could pair a new daemon with an old/incompatible shared library.
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF)
if(ECHOION_STATIC_LINK)
	set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
	set(BUILD_SHARED_LIBS OFF)
	set(CMAKE_POSITION_INDEPENDENT_CODE ON)
    message(STATUS "Static GCC runtime linking enabled")
endif()

# Release artifacts should not expose checkout, dependency, or build-machine
# paths through __FILE__, std::source_location, or optional DWARF data. Keep
# developer builds unchanged so local diagnostics can still use absolute paths;
# scripts/release.sh enables this option for production builds.
option(ECHOION_REPRODUCIBLE_BUILD
    "Replace local source/build prefixes in compiler-generated paths" OFF)
if(ECHOION_REPRODUCIBLE_BUILD)
    if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
        set(_echoionPrefixMaps
            "${CMAKE_SOURCE_DIR}=Echoion"
            "${CMAKE_BINARY_DIR}=EchoionBuild")
        if(DEFINED CPM_Void_SOURCE AND NOT CPM_Void_SOURCE STREQUAL "")
            list(APPEND _echoionPrefixMaps
                "${CPM_Void_SOURCE}=VoidLibrary")
        endif()
        if(DEFINED CPM_VoidTeamspeak_SOURCE AND
                NOT CPM_VoidTeamspeak_SOURCE STREQUAL "")
            list(APPEND _echoionPrefixMaps
                "${CPM_VoidTeamspeak_SOURCE}=VoidTeamspeak")
        endif()
        foreach(_echoionPrefixMap IN LISTS _echoionPrefixMaps)
            add_compile_options(
                "$<$<COMPILE_LANGUAGE:C,CXX>:-ffile-prefix-map=${_echoionPrefixMap}>"
                "$<$<COMPILE_LANGUAGE:C,CXX>:-fmacro-prefix-map=${_echoionPrefixMap}>"
                "$<$<COMPILE_LANGUAGE:C,CXX>:-fdebug-prefix-map=${_echoionPrefixMap}>")
        endforeach()
        message(STATUS "Reproducible compiler path mapping enabled")
    else()
        message(WARNING
            "ECHOION_REPRODUCIBLE_BUILD is not supported by this compiler")
    endif()
endif()

# Include CPM
file(
    DOWNLOAD
    https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake
    EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791
)
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)

# Include PackageProject.cmake
CPMAddPackage(
    NAME PackageProject.cmake
    GITHUB_REPOSITORY TheLartians/PackageProject.cmake
    VERSION 1.11.2
)

# VoidLibrary — modular C++26 infrastructure (Json, Logging, Configuration,
# Plugin, Service, Async, Functional, System, Fsm, ...). Echoion's in-house
# infrastructure is migrated onto these Void:: targets.
# For local development against a working copy, configure with
#   -DCPM_Void_SOURCE=/path/to/VoidLibrary
# which CPM honours over the git checkout below.
CPMAddPackage(
    NAME Void
    GIT_REPOSITORY https://git.faumaray.ru/void/voidlibrary.git
    # Keep clean/container releases reproducible. CPM_Void_SOURCE still
    # overrides this revision for local dependency development.
    GIT_TAG ${ECHOION_VOID_REVISION}
    OPTIONS
        "VOID_ENABLE_TESTING OFF"
)

# Modern native TeamSpeak client library. Local development can point at the
# adjacent history-preserving extraction with:
#   -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak
CPMAddPackage(
    NAME VoidTeamspeak
    GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git
    # This revision supplies the typed administration API used by Standalone.
    GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION}
    OPTIONS
        "VOID_TEAMSPEAK_BUILD_TESTS OFF"
        "VOID_ENABLE_TESTING OFF"
)

set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
set(CXX_SCAN_FOR_MODULES OFF)
# GCC 16+ exposes experimental C++26 reflection (P2996) via -freflection.
# Void's header-only INTERFACE modules (Data/Functional/Core) do not propagate
# this flag, so apply it tree-wide for every echoion target that may include
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
    # Guard to C++ only — vendored C dependencies (quickjs) must not see it.
    add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-freflection>)
endif()

# Link-time optimisation for Release configs only (keeps Debug builds fast).
# Experimental C++26 reflection (-freflection) is a front-end feature and is
# orthogonal to GCC's LTO, but gate behind an option so it can be disabled if a
# given toolchain rejects the combination.
option(ECHOION_ENABLE_LTO "Enable interprocedural optimisation for Release builds" ON)
if(ECHOION_ENABLE_LTO)
    include(CheckIPOSupported)
    check_ipo_supported(RESULT _ipoSupported OUTPUT _ipoError LANGUAGES CXX)
    if(_ipoSupported)
        set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
        set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO ON)
        message(STATUS "Interprocedural optimisation (LTO) enabled for Release")
    else()
        message(STATUS "IPO/LTO not supported by toolchain: ${_ipoError}")
    endif()
endif()

# Unity builds batch translation units to cut compile time. Kept OFF by default
# because reflection TUs and Glaze-heavy headers can blow up unity batch memory;
# enable per-machine with -DECHOION_UNITY_BUILD=ON.
option(ECHOION_UNITY_BUILD "Enable CMake unity (jumbo) builds" OFF)
if(ECHOION_UNITY_BUILD)
    set(CMAKE_UNITY_BUILD ON)
    set(CMAKE_UNITY_BUILD_BATCH_SIZE 8)
    message(STATUS "Unity build enabled (batch size 8)")
endif()

# Enable folder organization in IDEs
set_property(GLOBAL PROPERTY USE_FOLDERS ON)

# Options
option(BUILD_API "Build EchoionApi" ON)
option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb browser dashboard" ON)
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON)
option(BUILD_TESTS "Build tests" OFF)

if(BUILD_TESTS)
    enable_testing()
endif()

# Find packages
find_package(Threads REQUIRED)

# Add subdirectories
if(BUILD_API)
    add_subdirectory(EchoionApi)
endif()

if(BUILD_FIRST_PARTY_PLUGINS)
	add_subdirectory(plugins)
endif()

if(BUILD_STANDALONE)
    add_subdirectory(EchoionHost)
endif()

if(BUILD_CORE)
    add_subdirectory(EchoionCore)
endif()

# EchoionWeb is added after Core so it can reuse the single Boost header
# targets Core discovers. Core owns and starts the web server, so link them
# here (both targets now exist) and flag Core so the wiring compiles in.
if(BUILD_WEB AND BUILD_CORE)
    add_subdirectory(EchoionWeb)
    if(TARGET EchoionCore AND TARGET EchoionWeb)
        target_link_libraries(EchoionCore PRIVATE EchoionWeb)
        target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
    endif()
endif()

# VoidTeamspeak is resolved above as a regular reusable package. The legacy
# TeamSpeak client plugin and in-tree protocol directories are no longer built.

# The updater is a deliberately small, dynamically linked lifecycle helper.
# It validates and journals local operations but leaves network/feed work to
# the daemon through typed request files. Define it before Standalone so the
# Linux release-staging test can use the real helper binary.
if(UNIX AND NOT APPLE)
    add_subdirectory(packaging/updater)
endif()

# EchoionStandalone links the host-common loader and native protocol client.
if(BUILD_STANDALONE)
    add_subdirectory(EchoionStandalone)
endif()

if(BUILD_DESKTOP)
    add_subdirectory(EchoionDesktop)
endif()

# The release install component is deliberately runtime-only.  Nested projects
# keep their normal SDK/development install rules, while scripts/release.sh uses
# this component as the single input to dependency collection and packaging.
option(ECHOION_INSTALL_RUNTIME_BUNDLE
    "Provide the relocatable Echoion Runtime install component" ON)
if(ECHOION_INSTALL_RUNTIME_BUNDLE)
    if(TARGET EchoionStandalone)
        if(UNIX AND NOT APPLE)
            set_target_properties(EchoionStandalone PROPERTIES
                INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}"
                INSTALL_RPATH_USE_LINK_PATH FALSE)
        endif()
        install(TARGETS EchoionStandalone
            RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
            COMPONENT Runtime)
    endif()

    if(TARGET EchoionCore)
        if(UNIX AND NOT APPLE)
            set_target_properties(EchoionCore PROPERTIES
                INSTALL_RPATH "$ORIGIN"
                INSTALL_RPATH_USE_LINK_PATH FALSE)
        endif()
        install(TARGETS EchoionCore
            RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
            LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
            COMPONENT Runtime)
    endif()

    if(TARGET EchoionWeb)
        install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/"
            DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web"
            COMPONENT Runtime)
    endif()

    install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json"
        DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
        COMPONENT Runtime)
    install(FILES
        "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in"
        "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.service.in"
        "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.timer.in"
        DESTINATION service
        COMPONENT Runtime)
    install(PROGRAMS
        "${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate-release-manifest.py"
        DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/tools"
        COMPONENT Runtime)

    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
        install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
            DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses"
            RENAME Echoion-LICENSE
            COMPONENT Runtime)
    endif()
endif()

# Bundling and deployment helpers
# Function to bundle Qt dependencies
function(bundle_qt_dependencies target)
    if(NOT TARGET ${target})
        return()
    endif()
    
    if(WIN32)
        find_program(WINDEPLOYQT windeployqt HINTS ${Qt6Core_DIR}/../../../bin)
        if(WINDEPLOYQT)
            add_custom_command(TARGET ${target} POST_BUILD
                COMMAND ${WINDEPLOYQT} 
                    --dir $<TARGET_FILE_DIR:${target}>/qt_libs
                    --release
                    --no-translations
                    --no-compiler-runtime
                    --no-opengl-sw
                    $<TARGET_FILE:${target}>
                COMMENT "Bundling Qt dependencies for ${target}"
            )
        endif()
    elseif(APPLE)
        find_program(MACDEPLOYQT macdeployqt HINTS ${Qt6Core_DIR}/../../../bin)
        if(MACDEPLOYQT)
            add_custom_command(TARGET ${target} POST_BUILD
                COMMAND ${MACDEPLOYQT} $<TARGET_FILE:${target}> -always-overwrite
                COMMENT "Bundling Qt dependencies for ${target}"
            )
        endif()
    endif()
endfunction()

# Function to install target with its dependencies
function(install_with_dependencies target)
    if(NOT TARGET ${target})
        return()
    endif()
    
    get_target_property(target_type ${target} TYPE)
    
    if(target_type STREQUAL "EXECUTABLE")
        install(TARGETS ${target}
            RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
            BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR}
        )
        
        # Bundle Qt if needed
        get_target_property(linked_libs ${target} LINK_LIBRARIES)
        if(linked_libs)
            foreach(lib ${linked_libs})
                if(lib MATCHES "Qt6::")
                    bundle_qt_dependencies(${target})
                    break()
                endif()
            endforeach()
        endif()
    elseif(target_type STREQUAL "SHARED_LIBRARY")
        install(TARGETS ${target}
            RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
            LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
            ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
        )
    endif()
endfunction()

# Apply bundling to targets after all subdirectories are added
if(BUILD_DESKTOP AND TARGET EchoionDesktop)
    install_with_dependencies(EchoionDesktop)
endif()

if(BUILD_CORE AND TARGET EchoionCore)
    install_with_dependencies(EchoionCore)
endif()

if(BUILD_TESTS AND UNIX)
    add_test(NAME echoion_release_manifest_packaging_tests
        COMMAND bash
            "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh"
            "${CMAKE_CURRENT_SOURCE_DIR}")
    add_test(NAME echoion_runtime_dependency_packaging_tests
        COMMAND bash
            "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh"
            "${CMAKE_CURRENT_SOURCE_DIR}")
    add_test(NAME echoion_release_archive_packaging_tests
        COMMAND bash
            "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh"
            "${CMAKE_CURRENT_SOURCE_DIR}")
    add_test(NAME echoion_frontend_license_packaging_tests
        COMMAND bash
            "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh"
            "${CMAKE_CURRENT_SOURCE_DIR}")
    add_test(NAME echoion_installer_packaging_tests
        COMMAND bash
            "${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh")
endif()

# The universal .tar.zst/.run workflow is the supported Linux distribution
# format.  Keep legacy CPack available for local Windows/macOS experiments,
# without publishing inaccurate DEB/RPM host-dependency metadata.
option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF)
if(ECHOION_ENABLE_LEGACY_CPACK)
    set(CPACK_PACKAGE_NAME "Echoion")
    set(CPACK_PACKAGE_VENDOR "Echoion")
    set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
    set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
    set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
    if(WIN32)
        set(CPACK_GENERATOR "ZIP;NSIS")
        set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
    elseif(APPLE)
        set(CPACK_GENERATOR "DragNDrop")
        set(CPACK_DMG_VOLUME_NAME "Echoion")
    else()
        set(CPACK_GENERATOR "TGZ")
    endif()
    include(CPack)
endif()

# Print configuration summary
message(STATUS "")
message(STATUS "Echoion Configuration:")
message(STATUS "  Version: ${PROJECT_VERSION}")
if(DEFINED ECHOION_RUNTIME_VERSION)
	message(STATUS "  Runtime release version: ${ECHOION_RUNTIME_VERSION}")
endif()
message(STATUS "  C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS "  Build API: ${BUILD_API}")
message(STATUS "  Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}")
message(STATUS "  Build Core: ${BUILD_CORE}")
message(STATUS "  Build Desktop: ${BUILD_DESKTOP}")
message(STATUS "  Build Web: ${BUILD_WEB}")
message(STATUS "  Build Standalone: ${BUILD_STANDALONE}")
message(STATUS "  Build Tests: ${BUILD_TESTS}")
message(STATUS "  Static Link: ${ECHOION_STATIC_LINK}")
message(STATUS "  Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
message(STATUS "")
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
message(STATUS "To build: cmake --build build")
message(STATUS "To install: cmake --install build --prefix <install_dir>")
message(STATUS "To release: scripts/release.sh --version <version>")
message(STATUS "")
