# Set WORKING_DIR in calling code to "${CMAKE_SOURCE_DIR}"

# Use git branch as project name if clones from git
find_package(Git)
if(GIT_FOUND)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} rev-parse --abbrev-ref HEAD
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_BRANCH
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} rev-parse --short HEAD
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_COMMIT_SHORT
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} rev-parse HEAD
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_COMMIT_LONG
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} describe --abbrev=0 --tags
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_TAG
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} config --get remote.origin.url
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_ORIGIN
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} rev-parse --show-toplevel
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_DIRECTORY
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} rev-parse --show-toplevel
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_REPO
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} config --get user.name
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_USER
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} config --get user.email
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_EMAIL
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)
	execute_process(
	  COMMAND ${GIT_EXECUTABLE} -C ${WORKING_DIR} status --porcelain
	  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
	  OUTPUT_VARIABLE GIT_DIRTY
	  OUTPUT_STRIP_TRAILING_WHITESPACE
	)

	get_filename_component(GIT_REPO "${GIT_REPO}" NAME)

	set(APP_NAME ${GIT_REPO})
	set(APP_VERSION ${GIT_TAG})

	if("${GIT_DIRTY}" STREQUAL "")
		set(GIT_DIRTY_STRING "")
		set(GIT_DIRTY_FLAG "no")

	else()
		set(GIT_DIRTY_STRING " (dirty)")
		set(GIT_DIRTY_FLAG "yes")
	endif()

	message(STATUS "REPO:          " ${GIT_REPO})
	message(STATUS "BRANCH:        " ${GIT_BRANCH})
	message(STATUS "LOCAL CHANGES: " ${GIT_DIRTY_FLAG})
else()
	set(GIT_BRANCH "N/A")
	set(GIT_COMMIT_SHORT "N/A")
	set(GIT_COMMIT_LONG "N/A")
	set(GIT_TAG "N/A")
	set(GIT_ORIGIN "N/A")
	set(GIT_DIRECTORY "N/A")
	set(GIT_REPO "N/A")
	set(GIT_USER "N/A")
	set(GIT_EMAIL "N/A")
endif()

configure_file(gitinfo.h.in gitinfo.h @ONLY NEWLINE_STYLE UNIX)