# SDK support library.
ADD_SUBDIRECTORY(sdk_lib)

# Main dv-runtime executable.
SET(DV_SRC_FILES
	log.cpp
	config.cpp
	config_server/config_server_actions.cpp
	config_server/config_server_connection.cpp
	config_server/config_server.cpp
	devices_discovery.cpp
	modules_discovery.cpp
	module.cpp
	types.cpp
	main.cpp)

IF(OS_WINDOWS)
	SET_SOURCE_FILES_PROPERTIES(../packaging/windows/windows.obj PROPERTIES GENERATED TRUE)
	SET(DV_SRC_FILES ${DV_SRC_FILES} ../packaging/windows/windows.obj)
ENDIF()

# Set full RPATH
LIST(APPEND CMAKE_INSTALL_RPATH ${USER_LOCAL_PREFIX}/${CMAKE_INSTALL_BINDIR})
LIST(APPEND CMAKE_INSTALL_RPATH ${USER_LOCAL_PREFIX}/${CMAKE_INSTALL_LIBDIR})

# Compile main dv-runtime executable.
ADD_EXECUTABLE(dv-runtime ${DV_SRC_FILES})

TARGET_LINK_LIBRARIES(dv-runtime PRIVATE dv::sdk Boost::filesystem Boost::program_options)

TARGET_COMPILE_OPTIONS(dv-runtime PRIVATE ${SYSTEM_WARN_CXX_FLAGS})

INSTALL(TARGETS dv-runtime DESTINATION ${CMAKE_INSTALL_BINDIR})

# Needed only by dv-runtime.
IF(OS_UNIX
   OR OS_LINUX
   OR OS_MACOS)
	# libdl needed for Boost::DLL and Boost::stacktrace on some platforms like Linux and MacOS X.
	TARGET_LINK_LIBRARIES(dv-runtime PRIVATE dl)
ENDIF()

# Atomics support for older architectures/systems.
INCLUDE(CheckAtomic)

IF(NEED_LIBATOMIC)
	MESSAGE(STATUS "Using libatomic for std::atomic in dv-runtime.")

	TARGET_LINK_LIBRARIES(dv-runtime PRIVATE atomic)
ENDIF()

# Search for external libraries with pkg-config.
INCLUDE(FindPkgConfig)

PKG_CHECK_MODULES(tcmalloc IMPORTED_TARGET libtcmalloc>=2.5)

# Google Perftools only make sense for the main executable. TCMalloc support (fast memory allocation, heap
# checking/profiling).
IF(tcmalloc_FOUND AND DVR_ENABLE_TCMALLOC)
	MESSAGE(STATUS "Google Perftools' TCMalloc support enabled.")

	TARGET_LINK_LIBRARIES(dv-runtime PRIVATE PkgConfig::tcmalloc)

	TARGET_COMPILE_OPTIONS(dv-runtime
						   PRIVATE "-fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free")
	TARGET_COMPILE_DEFINITIONS(dv-runtime PRIVATE "ENABLE_HEAP_PROFILER=1")
ENDIF()

# CPU Profiler not supported on Windows.
IF(NOT OS_WINDOWS)
	PKG_CHECK_MODULES(profiler IMPORTED_TARGET libprofiler>=2.5)

	# Profiler support (CPU profiling).
	IF(profiler_FOUND AND DVR_ENABLE_PROFILER)
		MESSAGE(STATUS "Google Perftools' CPU profiler support enabled.")

		TARGET_LINK_LIBRARIES(dv-runtime PRIVATE PkgConfig::profiler)

		TARGET_COMPILE_DEFINITIONS(dv-runtime PRIVATE "ENABLE_CPU_PROFILER=1")
	ENDIF()
ENDIF()
