#Enable or disable stacktraces based on the system
include(CheckIncludeFiles)
include(CheckIncludeFileCXX)
include(CheckLibraryExists)
#We need execinfo.h for backtrace()
CHECK_INCLUDE_FILES(execinfo.h  HAS_EXECINFO_H)
#We would like cxxabi.h and dlfcn.h for the name demangling..
CHECK_INCLUDE_FILES(dlfcn.h     HAS_DLFCN_H)
CHECK_INCLUDE_FILE_CXX(cxxabi.h HAS_CXXABI_H)
CHECK_LIBRARY_EXISTS(dl       dladdr    "" HAS_DLADDR_LIB)
CHECK_LIBRARY_EXISTS(execinfo backtrace "" HAS_EXECINFO_LIB)

#Without it, we simply can't do backtraces.
if (${HAS_EXECINFO_H})
  if (HAS_EXECINFO_LIB)
    set( Mercury_BACKTRACE_LINK_EXECINFO ON CACHE INTERNAL "Link libexecinfo for platforms where this is not in libdl")
  endif()
  if (HAS_DLADDR_LIB)
    set( Mercury_BACKTRACE_LINK_DL ON CACHE INTERNAL "Link libdl for platforms where this is not in the crt")
  endif()
  #enable it only in debug..
  if (CMAKE_BUILD_TYPE)
    if (${CMAKE_BUILD_TYPE} STREQUAL "Debug")
      set( Mercury_BACKTRACE_ENABLE ON CACHE BOOL "Enable stacktraces for terminating log messages")
    else()
      set( Mercury_BACKTRACE_ENABLE OFF CACHE BOOL "Enable stacktraces for terminating log messages")
    endif()
  else()
    message(FATAL_ERROR "Build type has to be declared first")
  endif()
  #allow us to do demangling!
  set( USE_DEMANGLE ON )
  if (NOT HAS_DLFCN_H)
    set( USE_DEMANGLE OFF )
  endif()
  if (NOT HAS_CXXABI_H)
    set( USE_DEMANGLE OFF )
  endif()
  if ( USE_DEMANGLE )
    set( Mercury_BACKTRACE_DEMANGLE ON CACHE BOOL "Enable demangling for stacktraces")
  else()
    set( Mercury_BACKTRACE_DEMANGLE OFF CACHE BOOL "Demangling not possible")
  endif()
else()
  set( Mercury_BACKTRACE_ENABLE OFF CACHE INTERNAL "execinfo.h not found - stacktrace not possible" )
  set( Mercury_BACKTRACE_DEMANGLE OFF CACHE INTERNAL "no backtraces anyway" )
endif()
mark_as_advanced( FORCE Mercury_BACKTRACE_ENABLE Mercury_BACKTRACE_DEMANGLE )