project(btlvf VERSION ${prplmesh_VERSION})

find_package(Python3 REQUIRED COMPONENTS Interpreter)

get_property(PythonTlvf TARGET tlvf PROPERTY PythonTlvf)
message("-- Inherited ${PythonTlvf} ...")

set(TLVF_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(TLVF_OUT ${TLVF_DIR}/AutoGenerated)
set(TLVF_COMMAND ${Python3_EXECUTABLE} ${PythonTlvf} ${TLVF_DIR}/src ${TLVF_DIR}/yaml ${TLVF_OUT} -c ${TLVF_DIR}/tlvf_conf.yaml)

message("-- Running ${TLVF_COMMAND} --print-dependencies...")
execute_process(
    COMMAND ${TLVF_COMMAND} --print-dependencies
    OUTPUT_VARIABLE TLVF_DEPENDENCIES
    RESULT_VARIABLE RET
)
if(NOT RET EQUAL 0)
    message(FATAL_ERROR "-- ${TLVF_COMMAND} --print-dependencies failed!")
endif()

message(STATUS "Generating Beerocks TLVF files...")
execute_process(
    COMMAND ${TLVF_COMMAND} --print-outputs
    OUTPUT_VARIABLE TLVF_OUTPUTS
    RESULT_VARIABLE RET
)
if(NOT RET EQUAL 0)
    message(FATAL_ERROR "-- ${PythonTlvf} --print-outputs failed!")
endif()

add_custom_command(
    COMMAND ${TLVF_COMMAND}
    DEPENDS ${TLVF_DEPENDENCIES} ${TLVF_DIR}/tlvf_conf.yaml
    OUTPUT ${TLVF_OUTPUTS}
    COMMENT "Generating the tlvf files."
)

file(GLOB TLVF_SOURCES ${TLVF_DIR}/src/src/*.c*)
add_library(${PROJECT_NAME} ${TLVF_OUTPUTS} ${TLVF_SOURCES})
set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${prplmesh_VERSION} SOVERSION ${prplmesh_VERSION_MAJOR})
set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "-fno-schedule-insns")
target_include_directories(${PROJECT_NAME}
    PUBLIC
        $<TARGET_PROPERTY:tlvf,INTERFACE_INCLUDE_DIRECTORIES>
        $<TARGET_PROPERTY:bcl,INTERFACE_INCLUDE_DIRECTORIES>
        $<BUILD_INTERFACE:${TLVF_OUT}/include>
        $<BUILD_INTERFACE:${TLVF_DIR}/src/include>
        $<INSTALL_INTERFACE:include>
    )

# set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "-Wl,-z,defs")
target_link_libraries(${PROJECT_NAME} PUBLIC bcl tlvf)

install(TARGETS ${PROJECT_NAME} EXPORT btlvfConfig
    ARCHIVE  DESTINATION ${CMAKE_INSTALL_LIBDIR}
    LIBRARY  DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME  DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY ${TLVF_OUT}/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(DIRECTORY ${TLVF_DIR}/src/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(EXPORT btlvfConfig NAMESPACE beerocks:: DESTINATION lib/cmake/beerocks/${PROJECT_NAME})
