cmake_minimum_required(VERSION 3.10)
function(_add_grpc_target_alias target)
    if(NOT TARGET ${target})
        message(FATAL_ERROR "${target} is not a target")
    endif()

    get_target_property(_aliased ${target} ALIASED_TARGET)
    if(_aliased)
        message(FATAL_ERROR "_add_grpc_target_alias only could be called with
the non-aliased target")
    endif()

    get_target_property(_type ${target} TYPE)
    if(NOT TARGET gRPC::${target})
        if(_type STREQUAL "EXECUTABLE")
            add_executable(gRPC::${target} ALIAS ${target})
        else()
            add_library(gRPC::${target} ALIAS ${target})
        endif()
    endif()
endfunction()

find_package(gRPC CONFIG)

if(TARGET grpc)
    _add_grpc_target_alias(grpc)
endif()
if(TARGET grpc++)
    _add_grpc_target_alias(grpc++)
endif()
if(TARGET grpc_cpp_plugin)
    _add_grpc_target_alias(grpc_cpp_plugin)
endif()

unset(WrapgRPC_FOUND)
if(gRPC_FOUND AND TARGET gRPC::grpc AND TARGET gRPC::grpc++ AND TARGET gRPC::grpc_cpp_plugin)
    set(WrapgRPC_FOUND TRUE)
elseif(EXISTS "${QT_PROTOBUF_SOURCE_DIR}/3rdparty/grpc/CMakeLists.txt")
    message(WARNING "Support for built-in gRPC will be discontinued soon. Please make sure that
you have recent version of gRPC installed in your system.")
    set(gRPC_BUILD_TESTS FALSE CACHE INTERNAL "" FORCE)
    set(protobuf_BUILD_TESTS FALSE CACHE INTERNAL "" FORCE)
    add_subdirectory("${QT_PROTOBUF_SOURCE_DIR}/3rdparty/grpc" EXCLUDE_FROM_ALL)

    _add_grpc_target_alias(grpc)
    _add_grpc_target_alias(grpc++)
    _add_grpc_target_alias(grpc_cpp_plugin)
    set(WrapgRPC_FOUND TRUE)
endif()
