# Dmitriy Vetutnev 2018
# ODANT 2018

find_path(PCRE_INCLUDE_DIR
    NAMES pcre.h
    PATHS ${CONAN_INCLUDE_DIRS_PCRE}
    NO_DEFAULT_PATH
)

find_library(PCRE_LIBRARY
    NAMES pcre pcred
    PATHS ${CONAN_LIB_DIRS_PCRE}
    NO_DEFAULT_PATH
)

find_library(PCREPOSIX_LIBRARY
    NAMES pcreposix pcreposixd
    PATHS ${CONAN_LIB_DIRS_PCRE}
    NO_DEFAULT_PATH
)

if(PCRE_INCLUDE_DIR)

    file(STRINGS ${PCRE_INCLUDE_DIR}/pcre.h DEFINE_PCRE_MAJOR REGEX "^#define PCRE_MAJOR")
    string(REGEX REPLACE "^.*PCRE_MAJOR +([0-9]+).*$" "\\1" PCRE_VERSION_MAJOR "${DEFINE_PCRE_MAJOR}")

    file(STRINGS ${PCRE_INCLUDE_DIR}/pcre.h DEFINE_PCRE_MINOR REGEX "^#define PCRE_MINOR")
    string(REGEX REPLACE "^.*PCRE_MINOR +([0-9]+).*$" "\\1" PCRE_VERSION_MINOR "${DEFINE_PCRE_MINOR}")

    set(PCRE_VERSION_STRING "${PCRE_VERSION_MAJOR}.${PCRE_VERSION_MINOR}")
    set(PCRE_VERSION ${PCRE_VERSION_STRING})
    set(PCRE_VERSION_COUNT 2)

endif()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PCRE
    REQUIRED_VARS PCRE_INCLUDE_DIR PCRE_LIBRARY
    VERSION_VAR PCRE_VERSION
)

if(PCRE_FOUND AND NOT TARGET PCRE::PCRE)

    add_library(PCRE::PCRE UNKNOWN IMPORTED)
    set_target_properties(PCRE::PCRE PROPERTIES
        IMPORTED_LOCATION ${PCRE_LIBRARY}
        INTERFACE_INCLUDE_DIRECTORIES ${PCRE_INCLUDE_DIR}
        INTERFACE_COMPILE_DEFINITIONS "${CONAN_COMPILE_DEFINITIONS_PCRE}"
    )

    mark_as_advanced(PCRE_INCLUDE_DIR PCRE_LIBRARY)

    set(PCRE_INCLUDE_DIRS ${PCRE_INCLUDE_DIR})
    set(PCRE_LIBRARIES ${PCRE_LIBRARY} ${PCREPOSIX_LIBRARY})
    set(PCRE_DEFINITIONS "${CONAN_COMPILE_DEFINITIONS_PCRE}")

endif()

