#
# Generates C++ sources from the .proto files
#
# grpc_generate_cpp (<SRCS> <HDRS> <DEST> [<ARGN>...])
#
#  GSRCS, PSRCS - variable to define with autogenerated source files
#  GHDRS, PSRCS - variable to define with autogenerated header files
#  DEST - directory where the source files will be created
#  ARGN - .proto files
#
function(GENERATE_CPP GSRCS GHDRS PSRCS PHDRS DEST)
  if(NOT ARGN)
    message(SEND_ERROR "Error: GENERATE_CPP() called without any proto files")
    return()
  endif()
  
  set(PROTO_PATH)
  # Create an include path for each file specified
  foreach(FIL ${ARGN})
    get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
    get_filename_component(ABS_PATH ${ABS_FIL} PATH)

    list(FIND PROTO_PATH ${ABS_PATH} _contains_already)
    if(${_contains_already} EQUAL -1)
        list(APPEND PROTO_PATH ${ABS_PATH})
    endif()
  endforeach()

  message(STATUS "Using Proto Path: ${PROTO_PATH}")

  set(G_SRCS)
  set(G_HDRS)
  set(P_SRCS)
  set(P_HDRS)

  foreach(FIL ${ARGN})
    get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
    get_filename_component(FIL_WE ${FIL} NAME_WE)

    list(APPEND G_SRCS "${DEST}/${FIL_WE}.grpc.pb.cc")
    list(APPEND G_HDRS "${DEST}/${FIL_WE}.grpc.pb.h")
    list(APPEND P_SRCS "${DEST}/${FIL_WE}.pb.cc")
    list(APPEND P_HDRS "${DEST}/${FIL_WE}.pb.h")

    add_custom_command(
      OUTPUT "${DEST}/${FIL_WE}.grpc.pb.cc"
             "${DEST}/${FIL_WE}.grpc.pb.h"
             "${DEST}/${FIL_WE}.pb.cc"
             "${DEST}/${FIL_WE}.pb.h"
      COMMAND ${_PROTOBUF_PROTOC}
      ARGS --grpc_out "${DEST}"
        --cpp_out "${DEST}"
        -I "${PROTO_PATH}"
        --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
        "${ABS_FIL}"
      DEPENDS "${ABS_FIL}"
      COMMENT "Running C++ gRPC and Protobuf compiler on ${FIL}")
  endforeach()

  set(${GSRCS} ${G_SRCS} PARENT_SCOPE)
  set(${GHDRS} ${G_HDRS} PARENT_SCOPE)
  set(${PSRCS} ${P_SRCS} PARENT_SCOPE)
  set(${PHDRS} ${P_HDRS} PARENT_SCOPE)
endfunction()
