#
# hwloc: https://github.com/axboe/liburing
#
SET(LIBURING_PREFIX ${CMAKE_BINARY_DIR}/liburing)

# BIG NOTE: the "EXTERNAL_SOURCE_DIR" variable is used below to point to 
# the "external" directory. It must be set appropriately before this cmake file
# is included or it will default to CMAKE_SOURCE_DIR.
IF(NOT DEFINED EXTERNAL_SOURCE_DIR)
    SET(EXTERNAL_SOURCE_DIR ${CMAKE_SOURCE_DIR})
ENDIF()

IF(NOT DEFINED COMPILE_FLAGS)
    SET(COMPILE_FLAGS "-O3 -flto -march=haswell -mtune=generic")
    MESSAGE(STATUS "SETTING COMPILE_FLAGS")
ENDIF()


# Get number of for use in the BUILD_COMMAND below
INCLUDE(ProcessorCount)
ProcessorCount(N)

SET(liburing_static_lib ${LIBURING_PREFIX}/lib/liburing.a)

ExternalProject_Add(liburing_local
    PREFIX ${LIBURING_PREFIX}
    DOWNLOAD_COMMAND "" # fake this out since we already have the source
    SOURCE_DIR ${EXTERNAL_SOURCE_DIR}/external/liburing
    BINARY_DIR ${LIBURING_PREFIX}/src/liburing-build
    INSTALL_DIR ${LIBURING_PREFIX}
    # Bit of a hack... copy source into the build directory and build there
    # since autotools does not support out of tree builds. Also compile the 
    # static lib with -fPIC so it can be linked in the shared objects.
    #CONFIGURE_COMMAND sh -c "rsync -r ${EXTERNAL_SOURCE_DIR}/external/liburing/ ${LIBURING_PREFIX}/src/liburing-build && cd ${LIBURING_PREFIX}/src/liburing-build && autoreconf -f -i && AR=gcc-ar RANLIB=gcc-ranlib CFLAGS=\"-fPIC ${COMPILE_FLAGS}\" CXXFLAGS=\"-fPIC ${COMPILE_FLAGS}\" ${LIBURING_PREFIX}/src/hwloc-build/configure --with-pic --prefix=${LIBURING_PREFIX} --enable-shared=no --enable-static=yes --disable-opencl --disable-libxml2 --disable-cairo --disable-io"
    CONFIGURE_COMMAND sh -c "rsync -r ${EXTERNAL_SOURCE_DIR}/external/liburing/ ${LIBURING_PREFIX}/src/liburing-build && cd ${LIBURING_PREFIX}/src/liburing-build && ${LIBURING_PREFIX}/src/liburing-build/configure --prefix=${LIBURING_PREFIX} "
    BUILD_COMMAND make -j${N}
    INSTALL_COMMAND make install # install to directory ${CMAKE_BINARY_DIR} 
    BUILD_BYPRODUCTS ${liburing_static_lib}
)

INCLUDE_DIRECTORIES(${LIBURING_PREFIX}/include)

SET_SOURCE_FILES_PROPERTIES(
    ${liburing_static_lib} PROPERTIES
    EXTERNAL_OBJECT TRUE  # Identifies this as an object file (static lib)
    GENERATED TRUE        # Avoids need for file to exist at configure-time
)