CMAKE_MINIMUM_REQUIRED(VERSION 3.8.0)

FUNCTION(PATCH_SOURCES_EXECUTE _patchlist)
	FOREACH(_patch ${_patchlist})
		GET_FILENAME_COMPONENT(filename "${_patch}" NAME)
		MESSAGE(STATUS "Apply patch: ${filename}")
		EXECUTE_PROCESS(COMMAND "${PATCH_CMD}" ${PATCH_OPTIONS} ${_patch} RESULT_VARIABLE _result)

		IF(NOT _result EQUAL 0)
			MESSAGE(FATAL_ERROR "Patch failed with exit code: ${_result}")
		ENDIF()
	ENDFOREACH()
ENDFUNCTION()

FUNCTION(PATCH_SOURCES _component)
	SET(PATCHES_DIR @PROJECT_SOURCE_DIR@/patches)

	IF("@CMAKE_BUILD_TYPE@" STREQUAL "DEBUG")
		FILE(GLOB PATCHES_DEBUG "${PATCHES_DIR}/debug/${_component}-*.patch")
		PATCH_SOURCES_EXECUTE("${PATCHES_DEBUG}")
	ENDIF()

	FILE(GLOB PATCHES "${PATCHES_DIR}/${_component}-*.patch")
	PATCH_SOURCES_EXECUTE("${PATCHES}")
ENDFUNCTION()

MACRO(SEARCH_PATCH_CMD)
	IF(NOT DEFINED ENV{FORCE_PATCH_PY})
		FIND_PROGRAM(PATCH_CMD patch CMAKE_FIND_ROOT_PATH_BOTH)
	ENDIF()

	IF(PATCH_CMD)
		SET(PATCH_OPTIONS -p1 -i)
		MESSAGE(STATUS "Using 'patch' command... ${PATCH_CMD}")
	ELSE()
		MESSAGE(STATUS "Cannot find 'patch' command... using patch.py")

		IF(CMAKE_VERSION VERSION_LESS "3.12")
			FIND_PACKAGE(PythonInterp REQUIRED)
			SET(Python_EXECUTABLE ${PYTHON_EXECUTABLE})
		ELSE()
			FIND_PACKAGE(Python REQUIRED)
		ENDIF()

		SET(PATCH_CMD ${Python_EXECUTABLE})
		SET(PATCH_OPTIONS @PROJECT_SOURCE_DIR@/patch.py -p1 --debug -v)
	ENDIF()
ENDMACRO()



IF(COMPONENT MATCHES "qt|openssl")
	SEARCH_PATCH_CMD()
	PATCH_SOURCES(${COMPONENT})
ELSE()
	MESSAGE(FATAL_ERROR "Component unknown: ${COMPONENT}")
ENDIF()
