find_package(OpenEnclave CONFIG REQUIRED)

set(EDL ${CMAKE_CURRENT_SOURCE_DIR}/../tls_server.edl)

add_custom_command(
  OUTPUT tls_server_t.h tls_server_t.c tls_server_args.h
  DEPENDS ${EDL}
  COMMAND openenclave::oeedger8r --trusted ${EDL}
          --search-path ${OE_INCLUDEDIR}
          --search-path ${OE_INCLUDEDIR}/openenclave/edl
          --search-path ${OE_INCLUDEDIR}/openenclave/edl/sgx)

add_executable(
  tls_server_enclave
  ecalls.cpp
  ${CMAKE_CURRENT_BINARY_DIR}/tls_server_t.c)

target_include_directories(
  tls_server_enclave PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_BINARY_DIR}
    ${PROJECT_SOURCE_DIR}/src/interfaces/libpq/encryptsql/src/KeyDistribution/common)

target_link_libraries(
  tls_server_enclave
  keydistribution_common
  $<TARGET_OBJECTS:openenclave::oeseal_gcmaes> 
  openenclave::oeenclave
  openenclave::oecryptoopenssl
  openenclave::oecryptombedtls
  openenclave::oelibcxx
  openenclave::oehostsock
  openenclave::oehostresolver)

# 如需签名/生成 MRENCLAVE，可保留签名命令
# 用计算Enclave的密钥对签名 /etc/encryptsql/enclave/sign_enclave_private.pem
# 生成的enclave.signed在/new_enc/postgresql-14.2/src/interfaces/libpq/encryptsql/build/bin/tls_server_enclave.signed
add_custom_command(
  OUTPUT tls_server_enclave.signed tls_server_enc_mrenclave.h
  DEPENDS tls_server_enclave enc.conf
  COMMAND openenclave::oesign sign -e $<TARGET_FILE:tls_server_enclave>
          -c ${CMAKE_CURRENT_SOURCE_DIR}/enc.conf
          -k /etc/encryptsql/enclave/sign_enclave_private.pem
  COMMAND openenclave::oesign dump -e $<TARGET_FILE:tls_server_enclave>.signed
          > $<TARGET_FILE:tls_server_enclave>.info
  COMMAND bash /new_enc/postgresql-14.2/src/interfaces/libpq/encryptsql/src/KeyDistribution/scripts/gen_mrenclave_header.sh
          /new_enc/postgresql-14.2/src/interfaces/libpq/encryptsql/src/KeyDistribution/common/tls_server_enc_mrenclave.h
          $<TARGET_FILE:tls_server_enclave>.info)

add_custom_target(tls_server_sign ALL
                  DEPENDS tls_server_enclave.signed tls_server_enc_mrenclave.h)
