include(FindPackageHandleStandardArgs)
include(SelectLibraryConfigurations)

find_path(
	LIBXSLT_INCLUDE_DIR
	NAMES libxslt/xslt.h
)
find_library(
	LIBXSLT_LIBRARY_DEBUG
	NAMES libxsltd xsltd
)
find_library(
	LIBXSLT_LIBRARY_RELEASE
	NAMES libxslt xslt
)
select_library_configurations(LIBXSLT)

if(LIBXSLT_INCLUDE_DIR AND EXISTS "${LIBXSLT_INCLUDE_DIR}/libxslt/xsltconfig.h")
	file(STRINGS "${LIBXSLT_INCLUDE_DIR}/libxslt/xsltconfig.h" _LIBXSLT_VERSION_DEFINE REGEX "[\t ]*#define[\t ]+LIBXSLT_DOTTED_VERSION[\t ]+\"[^\"]*\".*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+LIBXSLT_DOTTED_VERSION[\t ]+\"([^\"]*)\".*" "\\1" LIBXSLT_VERSION "${_LIBXSLT_VERSION_DEFINE}")
	unset(_LIBXSLT_VERSION_DEFINE)
endif()

unset(_LIBXSLT_FIND_PACKAGE_ARGS)
set(LIBXSLT_INCLUDE_DIRS ${LIBXSLT_INCLUDE_DIR})
unset(_LIBXSLT_INTERFACE_LINK_LIBRARIES)
set(LIBXSLT_LIBRARIES ${LIBXSLT_LIBRARY})
unset(_LIBXSLT_REQUIRED_VARS)

if(LibXslt_FIND_QUIETLY)
	list(APPEND _LIBXSLT_FIND_PACKAGE_ARGS QUIET)
endif()
if(LibXslt_FIND_REQUIRED)
	list(APPEND _LIBXSLT_FIND_PACKAGE_ARGS REQUIRED)
endif()

find_package(LibXml2 ${_LIBXSLT_FIND_PACKAGE_ARGS})
list(APPEND LIBXSLT_INCLUDE_DIRS ${LIBXML2_INCLUDE_DIRS})
list(APPEND LIBXSLT_LIBRARIES ${LIBXML2_LIBRARIES})
list(APPEND _LIBXSLT_INTERFACE_LINK_LIBRARIES "LibXml2::LibXml2")
list(APPEND _LIBXSLT_REQUIRED_VARS LibXml2_FOUND)

find_package_handle_standard_args(
	LibXslt
	FOUND_VAR LibXslt_FOUND
	REQUIRED_VARS LIBXSLT_INCLUDE_DIR LIBXSLT_LIBRARY ${_LIBXSLT_REQUIRED_VARS}
	VERSION_VAR LIBXSLT_VERSION
)

if(LibXslt_FOUND AND NOT TARGET LibXslt::LibXslt)
	add_library(LibXslt::LibXslt UNKNOWN IMPORTED)
	if(LIBXSLT_LIBRARY_RELEASE)
		set_property(TARGET LibXslt::LibXslt APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
		set_target_properties(LibXslt::LibXslt PROPERTIES IMPORTED_LOCATION_RELEASE "${LIBXSLT_LIBRARY_RELEASE}")
	endif()
	if(LIBXSLT_LIBRARY_DEBUG)
		set_property(TARGET LibXslt::LibXslt APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
		set_target_properties(LibXslt::LibXslt PROPERTIES IMPORTED_LOCATION_DEBUG "${LIBXSLT_LIBRARY_DEBUG}")
	endif()
	set_target_properties(LibXslt::LibXslt PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${LIBXSLT_INCLUDE_DIRS}")
	set_target_properties(LibXslt::LibXslt PROPERTIES INTERFACE_LINK_LIBRARIES "${_LIBXSLT_INTERFACE_LINK_LIBRARIES}")
endif()

mark_as_advanced(LIBXSLT_INCLUDE_DIR)
unset(_LIBXSLT_FIND_PACKAGE_ARGS)
unset(_LIBXSLT_INTERFACE_LINK_LIBRARIES)
unset(_LIBXSLT_REQUIRED_VARS)
