# --------------- get git revision info ---------------

set(HAS_PUGS_GIT_INFO "TRUE")

find_package(Git QUIET)

if(GIT_FOUND)
  execute_process(
    COMMAND "${GIT_EXECUTABLE}" describe "--abbrev=0" "--match=v[0-9]*"
    WORKING_DIRECTORY "${PUGS_SOURCE_DIR}"
    OUTPUT_VARIABLE PUGS_GIT_TAG
    RESULT_VARIABLE FOUND_PUGS_GIT_INFO
    OUTPUT_STRIP_TRAILING_WHITESPACE)

  if(FOUND_PUGS_GIT_INFO EQUAL 0)
    execute_process(
      COMMAND "${GIT_EXECUTABLE}" reflog -1 "--format=%H"
      WORKING_DIRECTORY "${PUGS_SOURCE_DIR}"
      OUTPUT_VARIABLE PUGS_GIT_HASH
      OUTPUT_STRIP_TRAILING_WHITESPACE)

    execute_process(
      COMMAND "${GIT_EXECUTABLE}" symbolic-ref HEAD
      WORKING_DIRECTORY "${PUGS_SOURCE_DIR}"
      OUTPUT_VARIABLE PUGS_GIT_HEAD
      OUTPUT_STRIP_TRAILING_WHITESPACE)

    execute_process(
      COMMAND "${GIT_EXECUTABLE}" diff-index --quiet HEAD
      WORKING_DIRECTORY "${PUGS_SOURCE_DIR}"
      RESULT_VARIABLE STATE
      OUTPUT_STRIP_TRAILING_WHITESPACE)

    if(STATE EQUAL 0)
      set(PUGS_GIT_HAS_LOCAL_CHANGES "CLEAN")
      set(PUGS_GIT_IS_CLEAN true)
    else()
      set(PUGS_GIT_IS_CLEAN false)
      set(PUGS_GIT_HAS_LOCAL_CHANGES "DIRTY")
    endif()
  else()
    unset(HAS_PUGS_GIT_INFO)
  endif()
else()
  unset(HAS_PUGS_GIT_INFO)
endif()

if(FOUND_PUGS_GIT_INFO EQUAL 0)
  if(NOT("${PUGS_GIT_TAG}" STREQUAL "v${PUGS_VERSION}"))
    message("")
    message ("######  CMake code version  ${PUGS_VERSION} and")
    message ("######  git revision info  ${PUGS_GIT_TAG} do not match!")
    message("")
  endif()
else()
  message("")
  message ("######  This source tree is not a git repository!")
  message ("######  If you intend to change sources consider to clone a git repository!")
  message("")
endif()

# Generates revision header file candidate
configure_file("${PUGS_SOURCE_DIR}/src/utils/pugs_git_revision.hpp.in"
  "${CMAKE_CURRENT_BINARY_DIR}/pugs_git_revision"
  @ONLY)
