# Copyright 2015 AeonGames, Rodrigo Hernandez
# Licensed under the terms of the Apache 2.0 License.
function(gitclone repo path)
	if(NOT IS_DIRECTORY "${CMAKE_SOURCE_DIR}/${path}")
		message(STATUS "Cloning ${repo}, please wait")
		execute_process(COMMAND ${GIT_EXECUTABLE} clone ${repo} ${path} WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" RESULT_VARIABLE git_result OUTPUT_VARIABLE git_output ERROR_VARIABLE git_output)
		if(NOT git_result EQUAL 0)
			MESSAGE(FATAL_ERROR "Cloning ${repo} failed.\nResult: ${git_result}\nOutput: ${git_output}")
		endif(NOT git_result EQUAL 0)
	endif(NOT IS_DIRECTORY "${CMAKE_SOURCE_DIR}/${path}")
endfunction(gitclone repo path)

function(download url filename)
	if(NOT EXISTS "${CMAKE_SOURCE_DIR}/${filename}")
		message(STATUS "Downloading ${url}")
		file(DOWNLOAD "${url}" "${CMAKE_SOURCE_DIR}/${filename}" STATUS download_status SHOW_PROGRESS)
		list(GET download_status 0 download_status_code)
		list(GET download_status 1 download_status_desc)
		if(download_status_code)
			file(REMOVE "${CMAKE_SOURCE_DIR}/${filename}")
			message(FATAL_ERROR "Download failed\nError Code: ${download_status_code}\nMessage: ${download_status_desc}")
		endif()
		message(STATUS "Done downloading ${filename}")
	endif()
endfunction(download url filename)

function(decompress filename directory)
	if(NOT IS_DIRECTORY "${CMAKE_SOURCE_DIR}/${directory}")
		message(STATUS "Extracting ${filename} into ${CMAKE_SOURCE_DIR}")
		execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzvf "${CMAKE_SOURCE_DIR}/${filename}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" RESULT_VARIABLE extract_result)
		if(extract_result)
			message(FATAL_ERROR "Extracting Failed with error code: ${extract_result}")
		endif()
	endif()
endfunction(decompress filename directory)

function(decompress_into filename directory)
	if(NOT IS_DIRECTORY "${CMAKE_SOURCE_DIR}/${directory}")
		file(MAKE_DIRECTORY "${CMAKE_SOURCE_DIR}/${directory}")
		message(STATUS "Extracting ${filename} into ${CMAKE_SOURCE_DIR}/${directory}")
		execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzvf "${CMAKE_SOURCE_DIR}/${filename}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/${directory}" RESULT_VARIABLE extract_result)
		if(extract_result)
			message(FATAL_ERROR "Extracting Failed with error code: ${extract_result}")
		endif()
	endif()
endfunction(decompress_into filename directory)
