# - Try to find LibJemalloc
# Once done this will define
#  LIBJEMALLOC_FOUND - System has LibJemalloc
#  LIBJEMALLOC_INCLUDE_DIRS - The LibJemalloc include directories
#  LIBJEMALLOC_LIBRARIES - The libraries needed to use LibJemalloc
#  LIBJEMALLOC_DEFINITIONS - Compiler switches required for using LibJemalloc
#  LIBJEMALLOC_VERSION - LibJemalloc version

find_package(PkgConfig)
pkg_check_modules(PC_LIBJEMALLOC QUIET jemalloc)
set(LIBJEMALLOC_DEFINITIONS ${PC_LIBJEMALLOC_CFLAGS_OTHER})

find_path(LIBJEMALLOC_INCLUDE_DIR jemalloc/jemalloc.h
        HINTS ${PC_LIBJEMALLOC_INCLUDEDIR} ${PC_LIBJEMALLOC_INCLUDE_DIRS}
        )

find_library(LIBJEMALLOC_LIBRARY NAMES jemalloc libjemalloc
        HINTS ${PC_LIBJEMALLOC_LIBDIR} ${PC_LIBJEMALLOC_LIBRARY_DIRS})

if (NOT PC_LIBJEMALLOC_VERSION STREQUAL "")
    set(LIBJEMALLOC_VERSION ${PC_LIBJEMALLOC_VERSION})
elseif (EXISTS ${LIBJEMALLOC_INCLUDE_DIR}/pcre.h)
    # Read and parse version header file for version number
    file(READ ${LIBJEMALLOC_INCLUDE_DIR}/jemalloc/jemalloc.h _LIBJEMALLOC_HEADER_CONTENTS)
    if(_LIBJEMALLOC_HEADER_CONTENTS MATCHES ".*JEMALLOC_VERSION_MAJOR.*")
        string(REGEX REPLACE ".*JEMALLOC_VERSION_MAJOR ([0-9]+).*" "\\1" LIBJEMALLOC_VERSION_MAJOR "${_LIBJEMALLOC_HEADER_CONTENTS}")
        string(REGEX REPLACE ".*JEMALLOC_VERSION_MINOR +([0-9]+).*" "\\1" LIBJEMALLOC_VERSION_MINOR "${_LIBJEMALLOC_HEADER_CONTENTS}")
        string(REGEX REPLACE ".*JEMALLOC_VERSION_BUGFIX +([0-9]+).*" "\\1" LIBJEMALLOC_VERSION_BUGFIX "${_LIBJEMALLOC_HEADER_CONTENTS}")
        set(LIBJEMALLOC_VERSION "${LIBJEMALLOC_VERSION_MAJOR}.${LIBJEMALLOC_VERSION_MINOR}.${LIBJEMALLOC_VERSION_BUGFIX}")
    else ()
        set(LIBPCRE_VERSION 0.0.0)
    endif ()
else ()
    set(LIBJEMALLOC_VERSION 0.0.0)
endif ()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LibJemalloc
        REQUIRED_VARS LIBJEMALLOC_LIBRARY LIBJEMALLOC_INCLUDE_DIR
        VERSION_VAR LIBJEMALLOC_VERSION
        )

MARK_AS_ADVANCED(LIBJEMALLOC_LIBRARY LIBJEMALLOC_INCLUDE_DIR)

set(LIBJEMALLOC_LIBRARIES ${LIBJEMALLOC_LIBRARY})
set(LIBJEMALLOC_INCLUDE_DIRS ${LIBJEMALLOC_INCLUDE_DIR})
