cmake_minimum_required(VERSION 3.8)
project(mqtt_report)

# 设置RPATH策略：确保运行时从安装目录加载库
set(CMAKE_INSTALL_RPATH "$ORIGIN/../lib")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(mc REQUIRED)
find_package(radio_ctrl REQUIRED)
find_package(std_msgs REQUIRED)

file(GLOB MQTT_REPORT_SOURCES "src/*.cpp")

add_executable(mqtt_report_node ${MQTT_REPORT_SOURCES})

ament_target_dependencies(mqtt_report_node rclcpp mc std_msgs)

# 虚拟头文件库，包含项目头文件路径
add_library(mqtt_headers INTERFACE)
target_include_directories(mqtt_headers INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include)

target_compile_options(mqtt_headers INTERFACE -Wno-pedantic)
target_link_libraries(mqtt_report_node mqtt_headers)

# 包含 radio_ctrl 头文件
target_include_directories(mqtt_report_node
  PRIVATE ${radio_ctrl_INCLUDE_DIRS}
)

# 链接 radio_ctrl 库
target_link_libraries(mqtt_report_node
  ${radio_ctrl_LIBRARIES}
)

# ---- 关键：识别当前架构，选择对应 MQTT 库路径 ----
string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" SYSTEM_ARCH)

if(SYSTEM_ARCH MATCHES "aarch64|arm64")
  set(ARCH_DIR "arm64")
elseif(SYSTEM_ARCH MATCHES "x86_64|amd64")
  set(ARCH_DIR "x86")
else()
  message(FATAL_ERROR "Unsupported architecture: ${SYSTEM_ARCH}")
endif()

message(STATUS "Detected architecture: ${SYSTEM_ARCH}, using lib/${ARCH_DIR}/")

# 链接 MQTT 库
target_link_libraries(
  mqtt_report_node
  ${CMAKE_CURRENT_SOURCE_DIR}/lib/${ARCH_DIR}/libpaho-mqttpp3.so
  ${CMAKE_CURRENT_SOURCE_DIR}/lib/${ARCH_DIR}/libpaho-mqtt3as.so)

# 安装可执行文件
install(TARGETS mqtt_report_node DESTINATION lib/${PROJECT_NAME})

# 安装配置目录
install(DIRECTORY config DESTINATION share/${PROJECT_NAME})

# 安装当前架构下的 MQTT 库文件
install(
  FILES
    lib/${ARCH_DIR}/libpaho-mqtt3as.so.1.3.14
    lib/${ARCH_DIR}/libpaho-mqtt3as.so.1
    lib/${ARCH_DIR}/libpaho-mqtt3as.so
    lib/${ARCH_DIR}/libpaho-mqttpp3.so.1.5.1
    lib/${ARCH_DIR}/libpaho-mqttpp3.so.1
    lib/${ARCH_DIR}/libpaho-mqttpp3.so
  DESTINATION lib)

# ---- 测试相关配置（保持不变）----
if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  set(ament_cmake_copyright_FOUND TRUE)
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()
