##################################################################################################
#
# CMake script for finding leveldb.
#
# Cache variables (not intended to be used in CMakeLists.txt files)
#
# - leveldb_INCLUDE_DIR: Absolute path to package headers.
# - leveldb_LIBRARY: Absolute path to library.
#
#
# Output variables:
#
# - leveldb_FOUND: Boolean that indicates if the package was found
# - leveldb_INCLUDE_DIRS: Paths to the necessary header files
# - leveldb_LIBRARIES: Package libraries
#
# Example usage:
#
#  find_package(leveldb)
#  if(NOT leveldb_FOUND)
#    # Error handling
#  endif()
#  ...
#  include_directories(${leveldb_INCLUDE_DIRS} ...)
#  ...
#  target_link_libraries(my_target ${leveldb_LIBRARIES})
#
##################################################################################################

find_package(Threads REQUIRED)
find_package(leveldb CONFIG QUIET)

if (NOT leveldb_FOUND)

  # Get package location hint from environment variable (if any)
  if(NOT leveldb_ROOT_DIR AND DEFINED ENV{leveldb_ROOT_DIR})
      set(leveldb_ROOT_DIR "$ENV{leveldb_ROOT_DIR}" CACHE PATH
          "leveldb base directory location (optional, used for nonstandard installation paths)")
  endif()

   # Search path for nonstandard package locations
   if(leveldb_ROOT_DIR)
       set(leveldb_INCLUDE_PATH PATHS "${leveldb_ROOT_DIR}/include" NO_DEFAULT_PATH)
       set(leveldb_LIBRARY_PATH PATHS "${leveldb_ROOT_DIR}/lib"     NO_DEFAULT_PATH)
   else()
       set(leveldb_INCLUDE_PATH "")
       set(leveldb_LIBRARY_PATH "")
   endif()

    # Find headers and libraries
    find_path(leveldb_INCLUDE_DIR NAMES db.h PATH_SUFFIXES "leveldb" ${leveldb_INCLUDE_PATH})
    find_library(leveldb_LIBRARY  NAMES leveldb PATH_SUFFIXES "leveldb" ${leveldb_LIBRARY_PATH})

    mark_as_advanced(leveldb_INCLUDE_DIR leveldb_LIBRARY)

    # Output variables generation
    include(FindPackageHandleStandardArgs)
    find_package_handle_standard_args(leveldb DEFAULT_MSG leveldb_LIBRARY leveldb_INCLUDE_DIR)

    set(leveldb_FOUND ${LEVELDB_FOUND}) # Enforce case-correctness: Set appropriately cased variable...
    unset(LEVELDB_FOUND) # ...and unset uppercase variable generated by find_package_handle_standard_args

    if(leveldb_FOUND)
        set(leveldb_INCLUDE_DIR ${leveldb_INCLUDE_DIR})
        set(leveldb_LIBRARY ${leveldb_LIBRARY})

        if(NOT TARGET leveldb::leveldb)
            add_library(leveldb::leveldb UNKNOWN IMPORTED)
            set_property(TARGET leveldb::leveldb PROPERTY IMPORTED_LOCATION ${leveldb_LIBRARY})
            set_property(TARGET leveldb::leveldb PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${leveldb_INCLUDE_DIR})
        endif()
        list(APPEND leveldb_TARGETS leveldb::leveldb)
    elseif(leveldb_FIND_REQUIRED)
        message(FATAL_ERROR "Unable to find leveldb")
    endif()

else()
    message(STATUS "Found leveldb from installed package in ${leveldb_DIR}")
    list(APPEND leveldb_TARGETS leveldb::leveldb)
endif()
