# SPDX-License-Identifier: GPL-3.0-or-later

cmake_minimum_required(VERSION 3.25)
project(regex_pcre2_bridge LANGUAGES C)

if(NOT EMSCRIPTEN)
  message(FATAL_ERROR "The staged PCRE2 pack must be built with Emscripten.")
endif()

if(NOT DEFINED PCRE2_SOURCE_DIR OR NOT IS_DIRECTORY "${PCRE2_SOURCE_DIR}")
  message(FATAL_ERROR "PCRE2_SOURCE_DIR must identify the verified PCRE2 source checkout.")
endif()

if(NOT DEFINED REGEX_PCRE2_OUTPUT_DIR)
  message(FATAL_ERROR "REGEX_PCRE2_OUTPUT_DIR must identify the private staging directory.")
endif()

set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
set(BUILD_STATIC_LIBS ON CACHE BOOL "" FORCE)
set(PCRE2_BUILD_PCRE2_8 ON CACHE BOOL "" FORCE)
set(PCRE2_BUILD_PCRE2_16 OFF CACHE BOOL "" FORCE)
set(PCRE2_BUILD_PCRE2_32 OFF CACHE BOOL "" FORCE)
set(PCRE2_BUILD_PCRE2GREP OFF CACHE BOOL "" FORCE)
set(PCRE2_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(PCRE2_DEBUG OFF CACHE STRING "" FORCE)
set(PCRE2_REBUILD_CHARTABLES OFF CACHE BOOL "" FORCE)
set(PCRE2_SHOW_REPORT OFF CACHE BOOL "" FORCE)
set(PCRE2_STATIC_PIC OFF CACHE BOOL "" FORCE)
set(PCRE2_SUPPORT_JIT OFF CACHE BOOL "" FORCE)
set(PCRE2_SUPPORT_UNICODE ON CACHE BOOL "" FORCE)

add_subdirectory("${PCRE2_SOURCE_DIR}" pcre2-source EXCLUDE_FROM_ALL)

add_executable(regex-pcre2-pack pcre2_bridge.c)
target_compile_features(regex-pcre2-pack PRIVATE c_std_11)
target_compile_definitions(regex-pcre2-pack PRIVATE PCRE2_CODE_UNIT_WIDTH=8)
target_compile_options(
  regex-pcre2-pack
  PRIVATE
    -O3
    -fno-ident
    -fvisibility=hidden
)
target_link_libraries(regex-pcre2-pack PRIVATE pcre2-8-static)
target_link_options(
  regex-pcre2-pack
  PRIVATE
    -O3
    --no-entry
    "SHELL:-s ALLOW_MEMORY_GROWTH=1"
    "SHELL:-s ASSERTIONS=0"
    "SHELL:-s ENVIRONMENT=web,worker,node"
    "SHELL:-s EXPORT_ES6=1"
    "SHELL:-s EXPORT_NAME=createRegexPcre2"
    "SHELL:-s EXPORTED_FUNCTIONS=['_regex_pcre2_bridge_abi_version','_regex_pcre2_compile_probe','_regex_pcre2_config_flags','_regex_pcre2_error_message','_regex_pcre2_execute','_regex_pcre2_self_test','_regex_pcre2_substitute','_regex_pcre2_trace','_regex_pcre2_version','_malloc','_free']"
    "SHELL:-s EXPORTED_RUNTIME_METHODS=['HEAPU8','UTF8ToString']"
    "SHELL:-s FILESYSTEM=0"
    "SHELL:-s INITIAL_MEMORY=16777216"
    "SHELL:-s MALLOC=emmalloc"
    "SHELL:-s MAXIMUM_MEMORY=268435456"
    "SHELL:-s MODULARIZE=1"
    "SHELL:-s NO_EXIT_RUNTIME=1"
    "SHELL:-s STRICT=1"
)
set_target_properties(
  regex-pcre2-pack
  PROPERTIES
    OUTPUT_NAME pcre2
    RUNTIME_OUTPUT_DIRECTORY "${REGEX_PCRE2_OUTPUT_DIR}"
    SUFFIX ".mjs"
)
