project(tlvf VERSION ${prplmesh_VERSION})

find_package(Python3 REQUIRED COMPONENTS Interpreter)

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

set(ENUM_AUTO_PRINT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../external/enumAutoPrint)
set(ENUM_AUTO_PRINT_COMMAND ${ENUM_AUTO_PRINT_DIR}/enum_auto_print.py)

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("Dependencies=${TLVF_DEPENDENCIES}")
message("-- Running ${TLVF_COMMAND} --print-outputs...")
execute_process(
    COMMAND ${TLVF_COMMAND} --print-outputs
    OUTPUT_VARIABLE TLVF_OUTPUTS
    RESULT_VARIABLE RET
)
if(NOT RET EQUAL 0)
    message(FATAL_ERROR "-- ${TLVF_COMMAND} --print-outputs failed!")
endif()
#message("TLVF_OUTPUTS\n${TLVF_OUTPUTS}")

execute_process(COMMAND ${ENUM_AUTO_PRINT_COMMAND})
if(NOT RET EQUAL 0)
    message(FATAL_ERROR "-- Running enum_auto_print.py failed!")
endif()

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

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

# Add a custom property to the tlvf library to point to tlvf.py
set_target_properties(tlvf PROPERTIES PythonTlvf ${PythonTlvf})

install(TARGETS tlvf EXPORT TlvfConfig
    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 TlvfConfig DESTINATION lib/cmake/Tlvf)
install(PROGRAMS ${TLVF_DIR}/tlvf.py DESTINATION host/bin)

add_subdirectory(test)
message("-- Done")
