# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2025 ai-ad4 and the FreePDFEditor contributors
# src/ipc/CMakeLists.txt — the M1 IPC layer (§2.1, ADR-0004).
#
# Qt-free so it is unit-testable without a QApplication. Links QPDF (the
# document process reads PDFs from the handed fd), Cap'n Proto (the RPC
# transport), and libseccomp (the sandbox). The Qt adapter that marshals
# results back to the GUI thread lives in src/app.

find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
    pkg_check_modules(QPDF libqpdf IMPORTED_TARGET)
    pkg_check_modules(SECCOMP libseccomp IMPORTED_TARGET)
    pkg_check_modules(CAPNP capnp-rpc capnp IMPORTED_TARGET)
endif()
find_program(CAPNP_EXECUTABLE NAMES capnp capnpc)

set(_fpe_ipc_deps_ok ON)
if(NOT TARGET PkgConfig::QPDF)
    message(STATUS "QPDF not found — src/ipc will not be built.")
    set(_fpe_ipc_deps_ok OFF)
endif()
if(NOT TARGET PkgConfig::SECCOMP)
    message(STATUS "libseccomp not found — src/ipc will not be built.")
    set(_fpe_ipc_deps_ok OFF)
endif()
if(NOT TARGET PkgConfig::CAPNP OR NOT CAPNP_EXECUTABLE)
    message(STATUS "Cap'n Proto or the capnp compiler not found — src/ipc will not be built.")
    set(_fpe_ipc_deps_ok OFF)
endif()

if(_fpe_ipc_deps_ok)
    # Generate the C++ from the IPC schema with the capnp compiler directly
    # (the Debian CapnProto CMake config hard-requires libatomic via a check
    # that fails on x86-64 where it isn't needed; pkg-config has no such
    # check — see ~/memories/gitea-freepdfeditor.md).
    set(_schema ${CMAKE_CURRENT_SOURCE_DIR}/ipc.capnp)
    set(_gen_dir ${CMAKE_CURRENT_BINARY_DIR}/generated)
    set(_gen_hdr ${_gen_dir}/ipc.capnp.h)
    set(_gen_src ${_gen_dir}/ipc.capnp.c++)
    file(MAKE_DIRECTORY ${_gen_dir})
    add_custom_command(
        OUTPUT ${_gen_hdr} ${_gen_src}
        COMMAND ${CAPNP_EXECUTABLE} compile
                --src-prefix=${CMAKE_CURRENT_SOURCE_DIR}
                -I${CAPNP_INCLUDE_DIRS}
                -oc++:${_gen_dir}
                ${_schema}
        DEPENDS ${_schema}
        COMMENT "Generating Cap'n Proto C++ for the M1 IPC schema"
        VERBATIM)

    add_library(freepdfeditor_ipc STATIC
        FdPassing.cpp
        FdPassing.h
        Sandbox.cpp
        Sandbox.h
        DocumentProcessServer.cpp
        DocumentProcessServer.h
        DocumentProcessClient.cpp
        DocumentProcessClient.h
        ProcessLauncher.cpp
        ProcessLauncher.h
        ${_gen_src}
    )
    target_include_directories(freepdfeditor_ipc PUBLIC
        ${CMAKE_CURRENT_SOURCE_DIR}
        ${_gen_dir})
    target_link_libraries(freepdfeditor_ipc PUBLIC
        PkgConfig::QPDF
        PkgConfig::SECCOMP
        PkgConfig::CAPNP
        Threads::Threads)
    target_compile_features(freepdfeditor_ipc PUBLIC cxx_std_20)
    freepdfeditor_apply_warnings(freepdfeditor_ipc)
    freepdfeditor_apply_hardening(freepdfeditor_ipc)
endif()