cmake_minimum_required(VERSION 2.8)
find_program(GIT_EXECUTABLE git DOC "Git version control")
mark_as_advanced(GIT_EXECUTABLE)
find_file(GITDIR NAMES .git PATHS ${CMAKE_CURRENT_SOURCE_DIR} NO_DEFAULT_PATH)
find_file(VERSION_FILE NAMES version.py PATHS ${CMAKE_CURRENT_SOURCE_DIR} NO_DEFAULT_PATH)
if (NOT VERSION_FILE)
	message(SEND_ERROR "Missing version file \"version.py\"")
endif()
file(STRINGS "${VERSION_FILE}" GPICK_VERSION LIMIT_COUNT 1)
string(FIND ${GPICK_VERSION} "=" position)
string(LENGTH ${GPICK_VERSION} length)
math(EXPR position "${position} + 2")
math(EXPR length "${length} - ${position} - 1")
string(SUBSTRING ${GPICK_VERSION} ${position} ${length} GPICK_VERSION)
set(GPICK_BUILD_PLATFORM "${CMAKE_SYSTEM_NAME}")
if (GIT_EXECUTABLE AND GITDIR)
	set(old_tz $ENV{TZ})
	set(ENV{TZ} UTC)
	execute_process(COMMAND "${GIT_EXECUTABLE}" show --quiet "--date=format-local:%Y-%m-%d;%H:%M:%S" "--format=%H;%cd;"
		WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
		OUTPUT_VARIABLE version_parts
		ERROR_VARIABLE version_error
		OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	set(ENV{TZ} "${old_tz}")
	if (version_error)
		message(SEND_ERROR "Failed to get version: ${version_error}")
	endif()
	list(LENGTH version_parts length)
	if (length LESS 2)
		message(SEND_ERROR "Invalid version string ${version_parts}")
	endif()
	list(GET version_parts 0 GPICK_REVISION)
	list(GET version_parts 1 GPICK_BUILD_DATE)
	list(GET version_parts 2 GPICK_BUILD_TIME)
else()
	find_file(VERSION_TXT_FILE NAMES version.txt PATHS ${CMAKE_CURRENT_SOURCE_DIR} NO_DEFAULT_PATH)
	if (VERSION_TXT_FILE)
		file(STRINGS "${VERSION_TXT_FILE}" version_parts LIMIT_COUNT 3)
		list(GET version_parts 0 GPICK_REVISION)
		list(GET version_parts 1 GPICK_BUILD_DATE)
		list(GET version_parts 2 GPICK_BUILD_TIME)
		return()
	endif()
	set(GPICK_REVISION "unknown")
	set(GPICK_BUILD_DATE "")
	set(GPICK_BUILD_TIME "")
endif()
