find_package(Git)
if(GIT_EXECUTABLE AND IS_DIRECTORY ${CMAKE_SOURCE_DIR}/.git)
	execute_process(
		COMMAND ${GIT_EXECUTABLE} rev-list --count HEAD
		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
		OUTPUT_VARIABLE GIT_REV_COUNT
		OUTPUT_STRIP_TRAILING_WHITESPACE
	)

	execute_process(
		COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD
		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
		OUTPUT_VARIABLE GIT_SHORT_HASH
		OUTPUT_STRIP_TRAILING_WHITESPACE
	)

	execute_process(
		COMMAND ${GIT_EXECUTABLE} log -1 --format=%ad --date=short
		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
		OUTPUT_VARIABLE GIT_LAST_COMMIT_DATE
		OUTPUT_STRIP_TRAILING_WHITESPACE
	)

	execute_process(
		COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
		OUTPUT_VARIABLE GIT_BRANCH_NAME
		OUTPUT_STRIP_TRAILING_WHITESPACE
	)

	execute_process(
		COMMAND ${GIT_EXECUTABLE} describe --tags --exact-match HEAD
		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
		RESULT_VARIABLE GIT_NO_TAG
		OUTPUT_VARIABLE GIT_TAG_NAME
		ERROR_QUIET
		OUTPUT_STRIP_TRAILING_WHITESPACE
	)

	if(${GIT_NO_TAG})
		string(REPLACE "-" ";" GIT_LAST_COMMIT_DATE_LIST ${GIT_LAST_COMMIT_DATE})
		list(GET GIT_LAST_COMMIT_DATE_LIST 0 PROJECT_VERSION_MAJOR)
		list(GET GIT_LAST_COMMIT_DATE_LIST 1 PROJECT_VERSION_MINOR)
		set(PROJECT_VERSION_PATCH "r${GIT_REV_COUNT}-${GIT_SHORT_HASH}")
	endif()
else()
	set(GIT_NO_TAG TRUE)
	string(TIMESTAMP PROJECT_VERSION_MAJOR "%Y")
	string(TIMESTAMP PROJECT_VERSION_MINOR "%m")
	string(TIMESTAMP PROJECT_VERSION_PATCH "%d")
endif()

if(NOT GIT_EXECUTABLE OR GIT_NO_TAG)
	set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}")
else()
	set(PROJECT_VERSION "${GIT_TAG_NAME}")
endif()
message(STATUS "${TARGET_NAME} version: ${PROJECT_VERSION}")

mark_as_advanced(PROJECT_VERSION_MAJOR PROJECT_VERSION_MINOR PROJECT_VERSION_PATCH PROJECT_VERSION)
