# get arch information
execute_process(COMMAND getconf LONG_BIT OUTPUT_VARIABLE VAR_LONG_BIT)
if (VAR_LONG_BIT STREQUAL 32)
    set(SGX_ARCH x86)
elseif(CMAKE_CXX_FLAGS MATCHES -m32)
    set(SGX_ARCH x86)
endif()

if (SGX_ARCH STREQUAL x86)
    message(FATAL_ERROR "only x64 build is supported.")
else()
    set(SGX_COMMON_CFLAGS -m64)
    set(SGX_LIBRARY_PATH ${SGX_SDK}/lib64)
    set(SGX_ENCLAVE_SIGNER ${SGX_SDK}/bin/x64/sgx_sign)
    set(SGX_EDGER8R ${SGX_SDK}/bin/x64/sgx_edger8r)
endif()

if (SGX_MODE STREQUAL HW)
    set(SGX_URTS_LIB sgx_urts)
    set(SGX_USVC_LIB sgx_uae_service)
    set(SGX_TRTS_LIB sgx_trts)
    set(SGX_TSVC_LIB sgx_tservice)
else ()
    set(SGX_URTS_LIB sgx_urts_sim)
    set(SGX_USVC_LIB sgx_uae_service_sim)
    set(SGX_TRTS_LIB sgx_trts_sim)
    set(SGX_TSVC_LIB sgx_tservice_sim)
endif (SGX_MODE STREQUAL HW)

if (SGX_BUILD STREQUAL "DEBUG")
    set(SGX_COMMON_CFLAGS "${SGX_COMMON_CFLAGS} -O0 -g")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DDEBUG -UNDEBUG -UEDEBUG")
elseif(SGX_BUILD STREQUAL "PRERELEASE")
    set(SGX_COMMON_CFLAGS "${SGX_COMMON_CFLAGS} -O2")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -UDEBUG -DNDEBUG -DEDEBUG")
elseif(SGX_BUILD STREQUAL "RELEASE")
    if(SGX_MODE STREQUAL "HW")
        add_definitions(-DTC_SGX_IN_RELEASE_MODE)
        set(SGX_COMMON_CFLAGS "${SGX_COMMON_CFLAGS} -O2")
        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -UDEBUG -DNDEBUG -UEDEBUG")
    else()
        message(FATAL_ERROR "HW mode must be set with RELEASE")
    endif()
else()
    message(FATAL_ERROR "Unknown build ${SGX_BUILD}")
endif()

find_package(SGXPSW REQUIRED)

message(STATUS "SGX_SDK: ${SGX_SDK}")
message(STATUS "SGX_ARCH: ${SGX_ARCH}")
message(STATUS "SGX_MODE: ${SGX_MODE}")
message(STATUS "SGX_BUILD: ${SGX_BUILD}")
message(STATUS "SGX_LIBRARY_PATH: ${SGX_LIBRARY_PATH}")
message(STATUS "SGX_ENCLAVE_SIGNER: ${SGX_ENCLAVE_SIGNER}")
message(STATUS "SGX_EDGER8R: ${SGX_EDGER8R}")
message(STATUS "SGX_URTS_LIB: ${SGX_URTS_LIB}")
message(STATUS "SGX_USVC_LIB: ${SGX_USVC_LIB}")
message(STATUS "SGX_TRTS_LIB: ${SGX_TRTS_LIB}")
message(STATUS "SGX_TSVC_LIB: ${SGX_TSVC_LIB}")
message (STATUS "SGX uRTS path: ${SGX_URTS_LIBRARY}")
message (STATUS "SGX uSVC path: ${SGX_USVC_LIBRARY}")
message(STATUS "SGX_COMMON_CFLAGS: ${SGX_COMMON_CFLAGS}")
