
set(XLE_DXCOMPILER_DIR "" CACHE PATH "DirectXShaderCompiler artifacts directory")

macro(find_dxcompiler)

	if (NOT INTERNAL_LAST_XLE_DXCOMPILER_DIR STREQUAL XLE_DXCOMPILER_DIR)
		message("Detected change in DXCompiler configuration, searching again")
		set(INTERNAL_FOUND_DXCOMPILER_LIB)
		set(INTERNAL_FOUND_DXCOMPILER_DLL)
		set(INTERNAL_FOUND_DXIL_DLL)
		set(INTERNAL_DXCOMPILER_INCLUDE_DIR)
		set(INTERNAL_LAST_XLE_DXCOMPILER_DIR ${XLE_DXCOMPILER_DIR} CACHE STRING INTERNAL FORCE)
	endif ()

	if (NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
		message(FATAL_ERROR "find_dxcompiler has only be configured for 64 bit outputs")
	endif ()

	find_library(
		INTERNAL_FOUND_DXCOMPILER_LIB
		NAMES dxcompiler.lib
		HINTS ${XLE_DXCOMPILER_DIR}
		PATH_SUFFIXES lib/x64)

	find_file(
		INTERNAL_FOUND_DXCOMPILER_DLL
		NAMES dxcompiler.dll
		HINTS ${XLE_DXCOMPILER_DIR}
		PATH_SUFFIXES bin/x64)

	find_file(
		INTERNAL_FOUND_DXIL_DLL
		NAMES dxil.dll
		HINTS ${XLE_DXCOMPILER_DIR}
		PATH_SUFFIXES bin/x64)

	find_path(
		INTERNAL_DXCOMPILER_INCLUDE_DIR dxcapi.h
		HINTS ${XLE_DXCOMPILER_DIR}
		PATH_SUFFIXES inc)

	if (INTERNAL_FOUND_DXCOMPILER_LIB STREQUAL INTERNAL_FOUND_DXCOMPILER_LIB-NOTFOUND
		OR INTERNAL_FOUND_DXCOMPILER_DLL STREQUAL INTERNAL_FOUND_DXCOMPILER_DLL-NOTFOUND
		OR INTERNAL_FOUND_DXIL_DLL STREQUAL INTERNAL_FOUND_DXIL_DLL-NOTFOUND
		OR INTERNAL_DXCOMPILER_INCLUDE_DIR STREQUAL INTERNAL_DXCOMPILER_INCLUDE_DIR-NOTFOUND)

		message("INTERNAL_FOUND_DXCOMPILER_LIB: ${INTERNAL_FOUND_DXCOMPILER_LIB}")
		message("INTERNAL_FOUND_DXCOMPILER_DLL: ${INTERNAL_FOUND_DXCOMPILER_DLL}")
		message("INTERNAL_FOUND_DXIL_DLL: ${INTERNAL_FOUND_DXIL_DLL}")
		message("INTERNAL_DXCOMPILER_INCLUDE_DIR: ${INTERNAL_DXCOMPILER_INCLUDE_DIR}")
		message("XLE_DXCOMPILER_DIR: ${XLE_DXCOMPILER_DIR}")

		# See readme.md for more information about how to get the DirectXShaderCompiler
		message(FATAL_ERROR "Could not find DirectXShaderCompiler libraries and headers. Consider setting the XLE_DXCOMPILER_DIR cmake cache variable to the correct artifacts location.")
	endif ()

	mark_as_advanced(INTERNAL_FOUND_DXCOMPILER_LIB)
	mark_as_advanced(INTERNAL_FOUND_DXCOMPILER_DLL)
	mark_as_advanced(INTERNAL_FOUND_DXIL_DLL)
	mark_as_advanced(INTERNAL_DXCOMPILER_INCLUDE_DIR)

	add_library(dxcompiler IMPORTED SHARED GLOBAL)
	set_target_properties(dxcompiler PROPERTIES IMPORTED_LOCATION ${INTERNAL_FOUND_DXCOMPILER_DLL} IMPORTED_IMPLIB ${INTERNAL_FOUND_DXCOMPILER_LIB})
	set_target_properties(dxcompiler PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${INTERNAL_DXCOMPILER_INCLUDE_DIR})

	add_library(dxil IMPORTED SHARED GLOBAL)
	set_target_properties(dxil PROPERTIES IMPORTED_LOCATION ${INTERNAL_FOUND_DXIL_DLL} IMPORTED_IMPLIB ${INTERNAL_FOUND_DXCOMPILER_LIB})

endmacro ()
