# Find libxcrypt, the extended Unix password hashing library.
#
# This module defines:
#   Libxcrypt_FOUND
#   Libxcrypt_VERSION
#   Libxcrypt_INCLUDE_DIRS
#   Libxcrypt_LIBRARIES
#   Libxcrypt::Libxcrypt

find_package(PkgConfig QUIET)
pkg_check_modules(PC_LIBXCRYPT QUIET libxcrypt)

find_path(Libxcrypt_INCLUDE_DIR
  NAMES crypt.h
  HINTS ${PC_LIBXCRYPT_INCLUDE_DIRS}
)

if(STATIC AND NOT WIN32)
  find_file(Libxcrypt_LIBRARY
    NAMES libcrypt.a libxcrypt.a
    HINTS ${PC_LIBXCRYPT_LIBRARY_DIRS}
    PATH_SUFFIXES lib lib64
  )
else()
  find_library(Libxcrypt_LIBRARY
    NAMES crypt xcrypt
    HINTS ${PC_LIBXCRYPT_LIBRARY_DIRS}
  )
endif()

set(Libxcrypt_VERSION "${PC_LIBXCRYPT_VERSION}")

if(Libxcrypt_INCLUDE_DIR AND Libxcrypt_LIBRARY)
  include(CheckCSourceCompiles)
  set(_libxcrypt_required_includes "${CMAKE_REQUIRED_INCLUDES}")
  set(_libxcrypt_required_libraries "${CMAKE_REQUIRED_LIBRARIES}")
  set(CMAKE_REQUIRED_INCLUDES "${Libxcrypt_INCLUDE_DIR}")
  set(CMAKE_REQUIRED_LIBRARIES "${Libxcrypt_LIBRARY}")
  check_c_source_compiles(
    "#include <crypt.h>
     int main(void) { return crypt(\"password\", \"$6$salt\") == 0; }"
    Libxcrypt_HAS_CRYPT
  )
  set(CMAKE_REQUIRED_INCLUDES "${_libxcrypt_required_includes}")
  set(CMAKE_REQUIRED_LIBRARIES "${_libxcrypt_required_libraries}")
  unset(_libxcrypt_required_includes)
  unset(_libxcrypt_required_libraries)
endif()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Libxcrypt
  REQUIRED_VARS Libxcrypt_INCLUDE_DIR Libxcrypt_LIBRARY Libxcrypt_HAS_CRYPT
  VERSION_VAR Libxcrypt_VERSION
)

if(Libxcrypt_FOUND)
  set(Libxcrypt_INCLUDE_DIRS "${Libxcrypt_INCLUDE_DIR}")
  set(Libxcrypt_LIBRARIES "${Libxcrypt_LIBRARY}")

  if(NOT TARGET Libxcrypt::Libxcrypt)
    add_library(Libxcrypt::Libxcrypt UNKNOWN IMPORTED)
    set_target_properties(Libxcrypt::Libxcrypt PROPERTIES
      IMPORTED_LOCATION "${Libxcrypt_LIBRARY}"
      INTERFACE_INCLUDE_DIRECTORIES "${Libxcrypt_INCLUDE_DIR}"
    )
  endif()
endif()

mark_as_advanced(Libxcrypt_INCLUDE_DIR Libxcrypt_LIBRARY)
