include(FindPackageHandleStandardArgs)
include(SelectLibraryConfigurations)

find_path(
	LIBLZMA_INCLUDE_DIR
	NAMES lzma.h
)
find_library(
	LIBLZMA_LIBRARY_DEBUG
	NAMES liblzmad lzmad
)
find_library(
	LIBLZMA_LIBRARY_RELEASE
	NAMES liblzma lzma
)
select_library_configurations(LIBLZMA)

if(LIBLZMA_INCLUDE_DIR AND EXISTS "${LIBLZMA_INCLUDE_DIR}/lzma/version.h")
	file(STRINGS "${LIBLZMA_INCLUDE_DIR}/lzma/version.h" _LZMA_VERSION_MAJOR_DEFINE REGEX "[\t ]*#define[\t ]+LZMA_VERSION_MAJOR[\t ]+[0-9]+.*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+LZMA_VERSION_MAJOR[\t ]+([0-9]+).*" "\\1" LZMA_VERSION_MAJOR "${_LZMA_VERSION_MAJOR_DEFINE}")
	file(STRINGS "${LIBLZMA_INCLUDE_DIR}/lzma/version.h" _LZMA_VERSION_MINOR_DEFINE REGEX "[\t ]*#define[\t ]+LZMA_VERSION_MINOR[\t ]+[0-9]+.*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+LZMA_VERSION_MINOR[\t ]+([0-9]+).*" "\\1" LZMA_VERSION_MINOR "${_LZMA_VERSION_MINOR_DEFINE}")
	file(STRINGS "${LIBLZMA_INCLUDE_DIR}/lzma/version.h" _LZMA_VERSION_PATCH_DEFINE REGEX "[\t ]*#define[\t ]+LZMA_VERSION_PATCH[\t ]+[0-9]+.*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+LZMA_VERSION_PATCH[\t ]+([0-9]+).*" "\\1" LZMA_VERSION_PATCH "${_LZMA_VERSION_PATCH_DEFINE}")
	if(NOT LZMA_VERSION_MAJOR STREQUAL "" AND NOT LZMA_VERSION_MINOR STREQUAL "" AND NOT LZMA_VERSION_PATCH STREQUAL "")
		set(LZMA_VERSION "${LZMA_VERSION_MAJOR}.${LZMA_VERSION_MINOR}.${LZMA_VERSION_PATCH}")
	endif()
	unset(_LZMA_VERSION_MAJOR_DEFINE)
	unset(_LZMA_VERSION_MINOR_DEFINE)
	unset(_LZMA_VERSION_PATCH_DEFINE)
endif()

set(LIBLZMA_INCLUDE_DIRS ${LIBLZMA_INCLUDE_DIR})
set(LIBLZMA_LIBRARIES ${LIBLZMA_LIBRARY})

find_package_handle_standard_args(
	LibLZMA
	FOUND_VAR LibLZMA_FOUND
	REQUIRED_VARS LIBLZMA_INCLUDE_DIR LIBLZMA_LIBRARY
	VERSION_VAR LZMA_VERSION
)

if(LibLZMA_FOUND AND NOT TARGET LibLZMA::LibLZMA)
	add_library(LibLZMA::LibLZMA UNKNOWN IMPORTED)
	if(LIBLZMA_LIBRARY_RELEASE)
		set_property(TARGET LibLZMA::LibLZMA APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
		set_target_properties(LibLZMA::LibLZMA PROPERTIES IMPORTED_LOCATION_RELEASE "${LIBLZMA_LIBRARY_RELEASE}")
	endif()
	if(LIBLZMA_LIBRARY_DEBUG)
		set_property(TARGET LibLZMA::LibLZMA APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
		set_target_properties(LibLZMA::LibLZMA PROPERTIES IMPORTED_LOCATION_DEBUG "${LIBLZMA_LIBRARY_DEBUG}")
	endif()
	set_target_properties(LibLZMA::LibLZMA PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${LIBLZMA_INCLUDE_DIRS}")
endif()

mark_as_advanced(LIBLZMA_INCLUDE_DIR)
