# Find the libunwind library
#
#  LIBUNWIND_FOUND       - True if libunwind was found.
#  LIBUNWIND_LIBRARIES   - The libraries needed to use libunwind
#  LIBUNWIND_INCLUDE_DIR - Location of unwind.h and libunwind.h

FIND_PATH(LIBUNWIND_INCLUDE_DIR libunwind.h)
IF (NOT LIBUNWIND_INCLUDE_DIR)
    MESSAGE(FATAL_ERROR "failed to find libunwind.h")
ELSEIF (NOT EXISTS "${LIBUNWIND_INCLUDE_DIR}/unwind.h")
    MESSAGE(FATAL_ERROR "libunwind.h was found, but unwind.h was not found in that directory.")
    SET(LIBUNWIND_INCLUDE_DIR "")
ENDIF()

FIND_LIBRARY(LIBUNWIND_GENERIC_LIBRARY "unwind")
IF (NOT LIBUNWIND_GENERIC_LIBRARY)
    MESSAGE(FATAL_ERROR "failed to find unwind generic library")
ELSE()
    MESSAGE(STATUS "Found unwind: ${LIBUNWIND_GENERIC_LIBRARY}")
ENDIF()
SET(LIBUNWIND_LIBRARIES ${LIBUNWIND_GENERIC_LIBRARY})

# For some reason, we have to link to two libunwind shared object files:
# one arch-specific and one not.
IF (CMAKE_SYSTEM_PROCESSOR MATCHES "^arm")
    SET(LIBUNWIND_ARCH "arm")
ELSEIF (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64")
    SET(LIBUNWIND_ARCH "x86_64")
ELSEIF (CMAKE_SYSTEM_PROCESSOR MATCHES "^i.86$")
    SET(LIBUNWIND_ARCH "x86")
ENDIF()

IF (LIBUNWIND_ARCH)
    FIND_LIBRARY(LIBUNWIND_SPECIFIC_LIBRARY "unwind-${LIBUNWIND_ARCH}")
    IF (NOT LIBUNWIND_SPECIFIC_LIBRARY)
        MESSAGE(FATAL_ERROR "failed to find unwind-${LIBUNWIND_ARCH}")
    ELSE()
        MESSAGE(STATUS "Found unwind-${LIBUNWIND_ARCH}: ${LIBUNWIND_SPECIFIC_LIBRARY}")
    ENDIF()
    SET(LIBUNWIND_LIBRARIES ${LIBUNWIND_LIBRARIES} ${LIBUNWIND_SPECIFIC_LIBRARY})
ENDIF(LIBUNWIND_ARCH)

MARK_AS_ADVANCED(LIBUNWIND_LIBRARIES LIBUNWIND_INCLUDE_DIR)
