# PCREPlugin - requires PCRE2

if(NOT PCRE2_FOUND)
    message(STATUS "PCREPlugin requires PCRE2, skipping")
    return()
endif()

add_3proxy_plugin(PCREPlugin
    SOURCES pcre_plugin.c
    COMPILE_DEFINITIONS PCRE2_CODE_UNIT_WIDTH=8
)

# Helper function to link PCRE2 with static linking on Linux/FreeBSD
function(link_pcre2_static TARGET_NAME)
    if(CMAKE_SYSTEM_NAME STREQUAL "Linux" OR
       CMAKE_SYSTEM_NAME MATCHES "FreeBSD|OpenBSD|NetBSD" OR
       CMAKE_SYSTEM_NAME STREQUAL "Unix")
        # Try to find static PCRE2 library
        find_library(PCRE2_STATIC_LIBRARY
            NAMES pcre2-8 libpcre2-8.a pcre2-8.a
            PATHS ${PC_PCRE2_LIBRARY_DIRS}
                  /usr/lib
                  /usr/local/lib
                  /lib
        )
        if(PCRE2_STATIC_LIBRARY)
            # Use static linking with GNU ld
            target_link_libraries(${TARGET_NAME} PRIVATE
                -Wl,-Bstatic
                ${PCRE2_STATIC_LIBRARY}
                -Wl,-Bdynamic
            )
            message(STATUS "Using static PCRE2: ${PCRE2_STATIC_LIBRARY}")
        else()
            # Fallback to dynamic linking if static library not found
            if(TARGET PCRE2::PCRE2)
                target_link_libraries(${TARGET_NAME} PRIVATE PCRE2::PCRE2)
            else()
                target_link_libraries(${TARGET_NAME} PRIVATE ${PCRE2_LIBRARIES})
            endif()
            message(STATUS "Static PCRE2 not found, using dynamic linking")
        endif()
    else()
        # Other platforms (macOS, Windows) - use standard linking
        if(TARGET PCRE2::PCRE2)
            target_link_libraries(${TARGET_NAME} PRIVATE PCRE2::PCRE2)
        else()
            target_link_libraries(${TARGET_NAME} PRIVATE ${PCRE2_LIBRARIES})
            if(PCRE2_INCLUDE_DIRS)
                target_include_directories(${TARGET_NAME} PRIVATE ${PCRE2_INCLUDE_DIRS})
            endif()
        endif()
    endif()
endfunction()

link_pcre2_static(PCREPlugin)
