# SPDX-FileCopyrightText: 2026 Cavanshirpro
# SPDX-License-Identifier: LGPL-3.0-only

cmake_minimum_required(VERSION 3.26)
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION" YLPLUGIN_VERSION LIMIT_COUNT 1)
project(YLPlugin VERSION ${YLPLUGIN_VERSION} LANGUAGES C CXX)
include(GNUInstallDirs)
include(CTest)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(YLPLUGIN_QT "Build optional Qt RCC adapter" OFF)
option(YLPLUGIN_SANITIZE "Address and undefined behavior sanitizers" OFF)
option(YLPLUGIN_FUZZ "Build Clang libFuzzer reader" OFF)
option(YLPLUGIN_BUILD_NODE "Build the Node-API addon" OFF)
option(YLPLUGIN_BUILD_JNI "Build the Java/Kotlin JNI bridge" OFF)
option(YLPLUGIN_BUILD_PYTHON_RUNTIME "Build a standalone C ABI shared runtime for ctypes wheels" OFF)
set(YLPLUGIN_LIBRARY_TYPE SHARED CACHE STRING "Core library type: SHARED or STATIC")
set_property(CACHE YLPLUGIN_LIBRARY_TYPE PROPERTY STRINGS SHARED STATIC)
if(NOT YLPLUGIN_LIBRARY_TYPE MATCHES "^(SHARED|STATIC)$")
  message(FATAL_ERROR "YLPLUGIN_LIBRARY_TYPE must be SHARED or STATIC")
endif()
set(YLPLUGIN_YLSPEC_SOURCE "" CACHE PATH "Existing YLSpec 0.1.2 source (otherwise find installed package)")
if(YLPLUGIN_SANITIZE AND NOT MSVC)
  add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer)
  add_link_options(-fsanitize=address,undefined)
endif()
if(YLPLUGIN_YLSPEC_SOURCE)
  set(YLSPEC_BUILD_CLI OFF CACHE BOOL "" FORCE)
  add_subdirectory("${YLPLUGIN_YLSPEC_SOURCE}" _ylspec)
else()
  find_package(YLSpec 0.1.2 CONFIG REQUIRED)
endif()
find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto)
find_package(nlohmann_json 3.11 CONFIG REQUIRED)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
find_package(ZSTD REQUIRED)
# FindOpenSSL's static pkg-config interface can also append a bare shared zstd.
# Use the explicit selected ZSTD target once, including for static SDK bundles.
if(YLPLUGIN_LIBRARY_TYPE STREQUAL "STATIC" AND OPENSSL_USE_STATIC_LIBS)
  get_target_property(ylp_crypto_links OpenSSL::Crypto INTERFACE_LINK_LIBRARIES)
  if(ylp_crypto_links)
    list(REMOVE_ITEM ylp_crypto_links zstd)
    set_property(TARGET OpenSSL::Crypto PROPERTY INTERFACE_LINK_LIBRARIES "${ylp_crypto_links}")
  endif()
endif()
find_package(Threads REQUIRED)
add_library(ylplugin ${YLPLUGIN_LIBRARY_TYPE} src/container/container.cpp src/metadata/profile.cpp
  src/crypto/crypto.cpp src/compatibility/preflight.cpp src/runtime/runtime.cpp
  src/container/extract.cpp src/c_api.cpp)
add_library(YLPlugin::ylplugin ALIAS ylplugin)
target_include_directories(ylplugin PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
  $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> PRIVATE src ${ZSTD_INCLUDE_DIR})
target_link_libraries(ylplugin PRIVATE OpenSSL::Crypto ZSTD::ZSTD ${CMAKE_DL_LIBS}
  Threads::Threads PUBLIC YLSpec::ylspec nlohmann_json::nlohmann_json)
target_compile_definitions(ylplugin PRIVATE YLPLUGIN_BUILD _FILE_OFFSET_BITS=64 YLPLUGIN_VERSION="${PROJECT_VERSION}")
if(YLPLUGIN_LIBRARY_TYPE STREQUAL "STATIC")
  target_compile_definitions(ylplugin PUBLIC YLPLUGIN_STATIC)
  set_target_properties(ylplugin PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON)
endif()
set_target_properties(ylplugin PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION 0 WINDOWS_EXPORT_ALL_SYMBOLS ON POSITION_INDEPENDENT_CODE ON)
if(MSVC)
  target_compile_options(ylplugin PRIVATE /W4 /permissive-)
else()
  target_compile_options(ylplugin PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
endif()
add_executable(ylplugin_cli tools/cli.cpp)
set_target_properties(ylplugin_cli PROPERTIES OUTPUT_NAME ylplugin)
target_link_libraries(ylplugin_cli PRIVATE YLPlugin::ylplugin OpenSSL::Crypto)
if(YLPLUGIN_BUILD_NODE OR YLPLUGIN_BUILD_JNI)
  add_library(ylplugin_bridge STATIC bindings/common/api.cpp)
  target_link_libraries(ylplugin_bridge PUBLIC ylplugin)
  target_include_directories(ylplugin_bridge PUBLIC bindings/common)
  set_target_properties(ylplugin_bridge PROPERTIES POSITION_INDEPENDENT_CODE ON)
endif()
if(YLPLUGIN_BUILD_NODE)
  if(NOT EXISTS "${NODE_INCLUDE_DIR}/node_api.h")
    message(FATAL_ERROR "Set NODE_INCLUDE_DIR to Node.js headers")
  endif()
  add_library(ylplugin_node MODULE bindings/node/addon.cpp)
  target_include_directories(ylplugin_node PRIVATE "${NODE_INCLUDE_DIR}")
  target_compile_definitions(ylplugin_node PRIVATE NAPI_VERSION=8)
  target_link_libraries(ylplugin_node PRIVATE ylplugin_bridge)
  if(WIN32)
    target_link_libraries(ylplugin_node PRIVATE "${NODE_LIBRARY}")
  elseif(APPLE)
    target_link_options(ylplugin_node PRIVATE -undefined dynamic_lookup)
  endif()
  # The Windows import library must not overwrite the static core ylplugin.lib.
  set_target_properties(ylplugin_node PROPERTIES PREFIX "" OUTPUT_NAME ylplugin SUFFIX ".node"
    ARCHIVE_OUTPUT_NAME ylplugin_node)
endif()
if(YLPLUGIN_BUILD_JNI)
  find_package(JNI REQUIRED COMPONENTS JVM)
  add_library(ylplugin_jni SHARED bindings/jni/jni.cpp)
  target_include_directories(ylplugin_jni PRIVATE ${JNI_INCLUDE_DIRS})
  target_link_libraries(ylplugin_jni PRIVATE ylplugin_bridge)
endif()
if(YLPLUGIN_BUILD_PYTHON_RUNTIME)
  if(NOT YLPLUGIN_LIBRARY_TYPE STREQUAL "STATIC")
    message(FATAL_ERROR "Standalone Python runtime requires YLPLUGIN_LIBRARY_TYPE=STATIC")
  endif()
  add_library(ylplugin_runtime SHARED src/c_api.cpp)
  target_compile_definitions(ylplugin_runtime PRIVATE YLPLUGIN_RUNTIME_EXPORT YLPLUGIN_BUILD YLPLUGIN_VERSION="${PROJECT_VERSION}")
  # c_api.cpp includes internal.hpp, so it needs OpenSSL's compile usage too.
  target_link_libraries(ylplugin_runtime PRIVATE ylplugin OpenSSL::Crypto)
endif()
# Bindings keep embedded crypto/core symbols private, avoiding collisions with
# a host (such as Node) that already has another OpenSSL build loaded.
foreach(ylp_binding_target ylplugin_node ylplugin_jni ylplugin_runtime)
  if(TARGET ${ylp_binding_target})
    set_target_properties(${ylp_binding_target} PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON)
    if(UNIX AND NOT APPLE)
      target_link_options(${ylp_binding_target} PRIVATE "LINKER:--exclude-libs,ALL")
    elseif(APPLE)
      set(ylp_exports "${CMAKE_CURRENT_BINARY_DIR}/${ylp_binding_target}.exports")
      if(ylp_binding_target STREQUAL "ylplugin_node")
        file(WRITE "${ylp_exports}" "_napi_register_module_v1\n_node_api_module_get_api_version_v1\n")
      elseif(ylp_binding_target STREQUAL "ylplugin_jni")
        file(WRITE "${ylp_exports}" "_Java_xyz_younglion_ylplugin_Native_open\n_Java_xyz_younglion_ylplugin_Native_close\n_Java_xyz_younglion_ylplugin_Native_invoke\n")
      else()
        file(WRITE "${ylp_exports}" "")
        file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/ylplugin/ylplugin.h" ylp_declarations REGEX "^YLP_API ")
        foreach(ylp_declaration IN LISTS ylp_declarations)
          string(REGEX MATCH "(ylp_[a-z_]+)\\(" ylp_match "${ylp_declaration}")
          if(ylp_match)
            file(APPEND "${ylp_exports}" "_${CMAKE_MATCH_1}\n")
          endif()
        endforeach()
      endif()
      target_link_options(${ylp_binding_target} PRIVATE "LINKER:-exported_symbols_list,${ylp_exports}")
    endif()
  endif()
endforeach()
if(YLPLUGIN_QT)
  find_package(Qt6 6.4 REQUIRED COMPONENTS Core)
  add_library(ylplugin_qt adapters/qt/rcc.cpp)
  add_library(YLPlugin::qt ALIAS ylplugin_qt)
  target_include_directories(ylplugin_qt PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
  target_link_libraries(ylplugin_qt PUBLIC YLPlugin::ylplugin Qt6::Core)
  install(TARGETS ylplugin_qt EXPORT YLPluginTargets)
endif()
if(BUILD_TESTING)
  add_executable(ylplugin_tests tests/core.cpp)
  target_link_libraries(ylplugin_tests PRIVATE ylplugin OpenSSL::Crypto Threads::Threads)
  target_compile_definitions(ylplugin_tests PRIVATE YLP_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
  add_test(NAME plugin_core COMMAND ylplugin_tests)
  add_executable(ylplugin_c_example examples/read.c)
  target_link_libraries(ylplugin_c_example PRIVATE ylplugin)
  add_library(ylplugin_native_fixture MODULE tests/native_fixture.c)
  target_include_directories(ylplugin_native_fixture PRIVATE include)
  add_library(ylplugin_native_example MODULE examples/native/plugin.c)
  target_include_directories(ylplugin_native_example PRIVATE include)
  add_executable(ylplugin_native_host examples/native/host.cpp)
  target_link_libraries(ylplugin_native_host PRIVATE ylplugin)
  add_test(NAME native_lifecycle COMMAND ylplugin_tests --native $<TARGET_FILE:ylplugin_native_fixture>)
  set_tests_properties(native_lifecycle PROPERTIES SKIP_RETURN_CODE 77)
  find_package(Python3 COMPONENTS Interpreter REQUIRED)
  add_test(NAME examples COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/examples.py $<TARGET_FILE:ylplugin_cli> $<TARGET_FILE:ylplugin_native_host> $<TARGET_FILE:ylplugin_native_example>)
  set(ylp_ffi_target ylplugin)
  if(YLPLUGIN_LIBRARY_TYPE STREQUAL "STATIC")
    if(TARGET ylplugin_runtime)
      set(ylp_ffi_target ylplugin_runtime)
    else()
      set(ylp_ffi_target "")
    endif()
  endif()
  if(ylp_ffi_target)
    add_test(NAME cli_and_python COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/integration.py $<TARGET_FILE:ylplugin_cli> $<TARGET_FILE:${ylp_ffi_target}>)
    add_test(NAME conformance_vectors COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/conformance.py $<TARGET_FILE:${ylp_ffi_target}>)
    add_test(NAME python_sdk COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/python_sdk.py $<TARGET_FILE:${ylp_ffi_target}>)
  endif()
  if(UNIX)
    add_test(NAME cli_signal_cancel COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/cli_cancel.py $<TARGET_FILE:ylplugin_cli>)
  endif()
  if(ylp_ffi_target AND YLPLUGIN_SANITIZE AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
    execute_process(COMMAND ${CMAKE_CXX_COMPILER} -print-file-name=libasan.so OUTPUT_VARIABLE ylp_asan OUTPUT_STRIP_TRAILING_WHITESPACE)
    execute_process(COMMAND ${CMAKE_CXX_COMPILER} -print-file-name=libstdc++.so OUTPUT_VARIABLE ylp_stdcpp OUTPUT_STRIP_TRAILING_WHITESPACE)
    set_tests_properties(cli_and_python conformance_vectors python_sdk PROPERTIES ENVIRONMENT
      "LD_PRELOAD=${ylp_asan}:${ylp_stdcpp};ASAN_OPTIONS=detect_leaks=0:halt_on_error=1;UBSAN_OPTIONS=halt_on_error=1")
  endif()
  if(YLPLUGIN_QT)
    add_executable(ylplugin_qt_tests tests/qt.cpp)
    target_link_libraries(ylplugin_qt_tests PRIVATE ylplugin_qt)
    target_compile_definitions(ylplugin_qt_tests PRIVATE YLP_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
    add_test(NAME qt_rcc_lifecycle COMMAND ylplugin_qt_tests)
    find_package(Qt6 6.4 QUIET COMPONENTS Qml Quick)
    if(TARGET Qt6::Qml AND TARGET Qt6::Quick)
      add_executable(ylplugin_qml_tests tests/qml.cpp)
      target_link_libraries(ylplugin_qml_tests PRIVATE ylplugin_qt Qt6::Qml Qt6::Quick)
      target_compile_definitions(ylplugin_qml_tests PRIVATE YLP_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
      add_test(NAME qml_engine_lifecycle COMMAND ylplugin_qml_tests)
      set_tests_properties(qml_engine_lifecycle PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software")
    endif()
  endif()
endif()
if(YLPLUGIN_FUZZ)
  if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    message(FATAL_ERROR "YLPLUGIN_FUZZ requires Clang")
  endif()
  target_compile_options(ylplugin PRIVATE -fsanitize=fuzzer-no-link,address,undefined)
  target_link_options(ylplugin PRIVATE -fsanitize=address,undefined)
  add_executable(ylplugin_fuzz tests/fuzz.cpp)
  target_link_libraries(ylplugin_fuzz PRIVATE ylplugin)
  target_compile_options(ylplugin_fuzz PRIVATE -fsanitize=fuzzer,address,undefined)
  target_link_options(ylplugin_fuzz PRIVATE -fsanitize=fuzzer,address,undefined)
endif()
install(TARGETS ylplugin ylplugin_cli EXPORT YLPluginTargets)
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(EXPORT YLPluginTargets NAMESPACE YLPlugin:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/YLPlugin)
include(CMakePackageConfigHelpers)
configure_package_config_file(cmake/YLPluginConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/YLPluginConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/YLPlugin)
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/YLPluginConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY SameMinorVersion)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/YLPluginConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/YLPluginConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/YLPlugin)
install(FILES cmake/FindZSTD.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/YLPlugin)
install(DIRECTORY docs/ schemas/ DESTINATION ${CMAKE_INSTALL_DATADIR}/ylplugin)
install(FILES LICENSE COPYING LICENSING.md SOURCES.md THIRD_PARTY_NOTICES.md
  DESTINATION ${CMAKE_INSTALL_DATADIR}/licenses/ylplugin)
