include(ExternalProject)

set(PCRE_TARGET_VERSION "10.36")
set(PCRE_DIR ${CMAKE_CURRENT_BINARY_DIR}/pcre2)
set(PCRE_C_FLAGS ${CMAKE_C_FLAGS})

if(WIN32)
  # We don't really care about warnings in PCRE
  string(REGEX REPLACE "( |^)/W[0-9]( |$)" "\\1" PCRE_C_FLAGS ${PCRE_C_FLAGS})
elseif(BUILD_SHARED_LIBS)
  set(PCRE_C_FLAGS "${PCRE_C_FLAGS} -fPIC")
endif()

set(PCRE_CMAKE_ARGS
  -DBUILD_SHARED_LIBS:BOOL=OFF
  -DBUILD_STATIC_LIBS:BOOL=ON
  -DCMAKE_C_FLAGS:STRING=${PCRE_C_FLAGS}
  -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
  -DCMAKE_INSTALL_LIBDIR:PATH=lib
  -DCMAKE_INSTALL_PREFIX:PATH=${PCRE_DIR}
  -DCMAKE_VERBOSE_MAKEFILE:BOOL=${CMAKE_VERBOSE_MAKEFILE}
  -DINSTALL_MSVC_PDB:BOOL=OFF
  -DPCRE2_BUILD_PCRE2_8:BOOL=ON
  -DPCRE2_BUILD_PCRE2_16:BOOL=OFF
  -DPCRE2_BUILD_PCRE2_32:BOOL=OFF
  -DPCRE2_BUILD_PCRE2GREP:BOOL=OFF
  -DPCRE2_BUILD_TESTS:BOOL=OFF
  -DPCRE2_SUPPORT_JIT:BOOL=OFF
  -DPCRE2_SUPPORT_LIBBZ2:BOOL=OFF
  -DPCRE2_SUPPORT_LIBEDIT:BOOL=OFF
  -DPCRE2_SUPPORT_LIBREADLINE:BOOL=OFF
  -DPCRE2_SUPPORT_VALGRIND:BOOL=OFF
  -DPCRE2_SUPPORT_LIBZ:BOOL=OFF
  )

ExternalProject_Add(pcre
  URL "http://ftp.pcre.org/pub/pcre/pcre2-${PCRE_TARGET_VERSION}.tar.gz"
  URL_HASH SHA256=b95ddb9414f91a967a887d69617059fb672b914f56fa3d613812c1ee8e8a1a37
  CMAKE_ARGS ${PCRE_CMAKE_ARGS}
  )

ExternalProject_Get_Property(pcre
  SOURCE_DIR
  )

if(WIN32 AND "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
  set(PCRE_POSTFIX "d")
endif()

set(OPENELP_PCRE_LICENSE_PATH "${SOURCE_DIR}/LICENCE")
set(PCRE_INCLUDE_DIRS "${PCRE_DIR}/include")
set(PCRE_LIBRARY_DIRS "${PCRE_DIR}/lib")
set(PCRE_LIBRARIES "pcre2-8${PCRE_POSTFIX}")
