cmake_minimum_required(VERSION 3.16)
project(grpcsimplechatserver LANGUAGES CXX)

find_package(gRPC CONFIG QUIET)
find_package(Protobuf CONFIG QUIET)

# gRPC servers require reference gRPC and protobuf implementation
if(NOT TARGET gRPC::grpc_cpp_plugin
    OR NOT TARGET gRPC::grpc++
    OR NOT TARGET protobuf::libprotobuf
    OR NOT TARGET protobuf::protoc)
    message(AUTOR_WARNING "gRPC is not found. The ${PROJECT_NAME} example won't be built.")
    return ()
endif()

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)

if(NOT DEFINED INSTALL_EXAMPLESDIR)
    set(INSTALL_EXAMPLESDIR "examples")
endif()

set(INSTALL_EXAMPLEDIR "${INSTALL_EXAMPLESDIR}/grpc/simplechatserver")

set(generated_sources
    "${CMAKE_CURRENT_BINARY_DIR}/simplechat.pb.cc"
    "${CMAKE_CURRENT_BINARY_DIR}/simplechat.grpc.pb.cc"
)
set_source_files_properties(${generated_sources} PROPERTIES GENERATED TRUE)

qt_add_executable(grpcsimplechatserver main.cpp ${generated_sources})
target_include_directories(grpcsimplechatserver PRIVATE ${CMAKE_CURRENT_BINARY_DIR})

_qt_internal_protobuf_reference_generate(TARGET grpcsimplechatserver
    GENERATED_SOURCES ${generated_sources}
    PROTO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/../simplechat/proto/simplechat.proto")

target_link_libraries(grpcsimplechatserver PRIVATE protobuf::libprotobuf gRPC::grpc++ gRPC::grpc)
if(MSVC)
    target_compile_definitions(grpcsimplechatserver PRIVATE _WIN32_WINNT=0x600 _SCL_SECURE_NO_WARNINGS _CRT_SECURE_NO_WARNINGS _WINSOCK_DEPRECATED_NO_WARNINGS)
endif()
if(UNIX AND "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
    target_compile_options(grpcsimplechatserver PRIVATE -Wno-error=array-bounds)
endif()

install(TARGETS grpcsimplechatserver
    RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
    BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
    LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
)

add_custom_command(TARGET grpcsimplechatserver
    COMMAND ${CMAKE_COMMAND} -E copy
            "${CMAKE_CURRENT_SOURCE_DIR}/../ssl/cert.pem"
            "${CMAKE_CURRENT_SOURCE_DIR}/../ssl/key.pem"
            "$<TARGET_FILE_DIR:grpcsimplechatserver>"
)

install(FILES
            "${CMAKE_CURRENT_SOURCE_DIR}/../ssl/cert.pem"
            "${CMAKE_CURRENT_SOURCE_DIR}/../ssl/key.pem"
        DESTINATION "${INSTALL_EXAMPLEDIR}"
)
