if(MBEDTLS_PREFER_STATIC_LIB)
    set(MBEDTLS_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
    if(WIN32)
        set(CMAKE_FIND_LIBRARY_SUFFIXES .a .lib ${CMAKE_FIND_LIBRARY_SUFFIXES})
    else()
        set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
    endif()
endif()

if(UNIX)
    find_package(PkgConfig QUIET)
    pkg_check_modules(_MBEDTLS QUIET mbedtls)
endif()

find_path(MBEDTLS_INCLUDE_DIR
    NAMES mbedtls/version.h
    HINTS ${_MBEDTLS_INCLUDEDIR})
find_library(MBEDTLS_LIBRARY
    NAMES mbedtls
    HINTS ${_MBEDTLS_LIBDIR})
find_library(MBEDCRYPTO_LIBRARY
    NAMES mbedcrypto
    HINTS ${_MBEDTLS_LIBDIR})

if(_MBEDTLS_VERSION)
    set(MBEDTLS_VERSION ${_MBEDTLS_VERSION})
elseif(MBEDTLS_INCLUDE_DIR)
    file(STRINGS "${MBEDTLS_INCLUDE_DIR}/mbedtls/version.h" MBEDTLS_VERSION_STR
        REGEX "^#define[\t ]+MBEDTLS_VERSION_STRING[\t ]+\"[^\"]+\"")
    if(MBEDTLS_VERSION_STR MATCHES "\"([^\"]+)\"")
        set(MBEDTLS_VERSION "${CMAKE_MATCH_1}")
    endif()
endif()

set(MBEDTLS_INCLUDE_DIRS ${MBEDTLS_INCLUDE_DIR})
set(MBEDTLS_LIBRARIES ${MBEDTLS_LIBRARY} ${MBEDCRYPTO_LIBRARY})

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(MbedTLS
    REQUIRED_VARS
        MBEDTLS_LIBRARY
        MBEDTLS_INCLUDE_DIR
    VERSION_VAR MBEDTLS_VERSION)

if(MBEDTLS_LIBRARY AND NOT TARGET MbedTLS::mbedtls)
    add_library(MbedTLS::mbedtls UNKNOWN IMPORTED)
    set_target_properties(MbedTLS::mbedtls PROPERTIES
        IMPORTED_LOCATION ${MBEDTLS_LIBRARY}
        INTERFACE_INCLUDE_DIRECTORIES ${MBEDTLS_INCLUDE_DIR}
    )
endif()

if(MBEDCRYPTO_LIBRARY AND NOT TARGET MbedTLS::mbedcrypto)
    add_library(MbedTLS::mbedcrypto UNKNOWN IMPORTED)
    set_target_properties(MbedTLS::mbedcrypto PROPERTIES
        IMPORTED_LOCATION ${MBEDCRYPTO_LIBRARY}
        INTERFACE_INCLUDE_DIRECTORIES ${MBEDTLS_INCLUDE_DIR}
    )
endif()

mark_as_advanced(MBEDTLS_INCLUDE_DIR MBEDTLS_LIBRARY MBEDCRYPTO_LIBRARY)

if(MBEDTLS_PREFER_STATIC_LIB)
    set(CMAKE_FIND_LIBRARY_SUFFIXES ${MBEDTLS_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES})
    unset(MBEDTLS_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES)
endif()
