INCLUDE(FindProtobuf)
FIND_PACKAGE(Protobuf 3 REQUIRED)
INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR} ${Protobuf_INCLUDE_DIRS})

FILE(GLOB all_protos "proto/foxglove/*.proto")

FOREACH(f ${all_protos})
    file(RELATIVE_PATH f ${CMAKE_CURRENT_SOURCE_DIR}/proto ${f})
    STRING(REGEX REPLACE "\\.proto$" "" f ${f})
    LIST(APPEND proto_sources "autogenerated/${f}.pb.h")
    LIST(APPEND proto_sources "autogenerated/${f}.pb.cc")
ENDFOREACH(f)

add_custom_command(
    OUTPUT ${proto_sources}
    COMMAND ${CMAKE_COMMAND} -E make_directory autogenerated
    COMMAND ${Protobuf_PROTOC_EXECUTABLE} --proto_path=${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=autogenerated ${all_protos}
)

add_library(foxglove_proto_lib ${proto_sources})
target_link_libraries(foxglove_proto_lib INTERFACE ${Protobuf_LIBRARIES})
target_include_directories(foxglove_proto_lib PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/autogenerated)
# Unfortunately the protobuf library headers include some unused parameters, which have to be
# downgraded back to warnings for all targets that depends on them.
if (MSVC)
    target_compile_options(foxglove_proto_lib PUBLIC /wd4100 /wd4267 /wd4244)
else()
    target_compile_options(foxglove_proto_lib PUBLIC -Wno-error=unused-parameter)
endif()

add_executable(example_protobuf_writer writer.cpp BuildFileDescriptorSet.cpp)
target_link_libraries(example_protobuf_writer ${CONAN_LIBS} foxglove_proto_lib)
target_compile_definitions(example_protobuf_writer PRIVATE _USE_MATH_DEFINES)

add_executable(example_protobuf_dynamic_reader dynamic_reader.cpp)
target_link_libraries(example_protobuf_dynamic_reader ${CONAN_LIBS} ${Protobuf_LIBRARIES})
if (MSVC)
    target_compile_options(example_protobuf_dynamic_reader PUBLIC /wd4100)
else()
    target_compile_options(example_protobuf_dynamic_reader PUBLIC -Wno-error=unused-parameter)
endif()

add_executable(example_protobuf_static_reader static_reader.cpp)
target_link_libraries(example_protobuf_static_reader ${CONAN_LIBS} foxglove_proto_lib)
if (MSVC)
    target_compile_options(example_protobuf_static_reader PUBLIC /wd4100)
else()
    target_compile_options(example_protobuf_static_reader PUBLIC -Wno-error=unused-parameter)
endif()

add_executable(example_protobuf_unit_tests unit_tests.cpp BuildFileDescriptorSet.cpp)
target_link_libraries(example_protobuf_unit_tests ${CONAN_LIBS} foxglove_proto_lib)
if (MSVC)
    target_compile_options(example_protobuf_unit_tests PUBLIC /wd4100)
else()
    target_compile_options(example_protobuf_unit_tests PUBLIC -Wno-error=unused-parameter)
endif()
