set(_CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ${CMAKE_FIND_ROOT_PATH_MODE_PROGRAM})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH)
set(_CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ${CMAKE_FIND_ROOT_PATH_MODE_INCLUDE})
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH)

if(CMAKE_HOST_WIN32)
	set(USER_HOME "$ENV{USERPROFILE}")
else()
	set(USER_HOME "$ENV{HOME}")
endif()

if(NOT DEFINED CARGO_HOME)
	if("$ENV{CARGO_HOME}" STREQUAL "")
		set(CARGO_HOME "${USER_HOME}/.cargo")
	else()
		set(CARGO_HOME "$ENV{CARGO_HOME}")
	endif()
endif()

# Find cargo executable
find_program(CBINDGEN_EXECUTABLE cbindgen
	HINTS "${CARGO_HOME}"
	PATH_SUFFIXES "bin")
mark_as_advanced(CBINDGEN_EXECUTABLE)

set(CBINDGEN_FOUND FALSE CACHE INTERNAL "")

if(CBINDGEN_EXECUTABLE)
	set(CBINDGEN_FOUND TRUE CACHE INTERNAL "")

	execute_process(COMMAND ${CBINDGEN_EXECUTABLE} --version OUTPUT_VARIABLE CBINDGEN_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE)
	string(REGEX REPLACE "cbindgen ([^ ]+) .*" "\\1" CBINDGEN_VERSION "${CBINDGEN_VERSION}")
endif()

if(NOT CBINDGEN_FOUND)
	message(FATAL_ERROR "Could not find cbindgen! Install with cargo install --force cbindgen")
endif()

set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ${_CMAKE_FIND_ROOT_PATH_MODE_PROGRAM})
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ${_CMAKE_FIND_ROOT_PATH_MODE_INCLUDE})
