#
# This script is called at build time via a custom command in GitVersion.cmake
# Its purpose is to query Git and configure a file with the obtained information
#
# Input variables:
#
#   SRC             Path to the source file for configure_file.
#   DST             Path to the destination file for configure_file.
#   GIT_EXECUTABLE  Path to the Git executable (e.g. from FindGit).
#   REPO            Path to any file in the repository to query.
#   NAMESPACE       Fully-qualified namespace to place the generated methods in.
#
# This script will use GIT_EXECUTABLE to query REPO and create the following
# variables which will be used to configured SRC into DST:
#
#   MAJOR_VERSION   Major version number from the git tag, or 0.
#   MINOR_VERSION   Minor version number from the git tag, or 0.
#   PATCH_VERSION   Patch version number from the git tag, or 0.
#   BUILD_COMMIT    Full Git commit SHA.
#   VERSION_CLEAN   "true" if the repo is clean, "false" otherwise.
#   VERSION_STRING  Stringified version with the major, minor and patch versions.
#
set(MAJOR_VERSION 0)
set(MINOR_VERSION 0)
set(PATCH_VERSION 0)
set(BUILD_COMMIT "")
set(VERSION_CLEAN "false")

if(GIT_EXECUTABLE AND REPO)
    # Get Git information
    execute_process(
        COMMAND ${GIT_EXECUTABLE} -C ${REPO} describe --tags --abbrev=0
        RESULT_VARIABLE ERRCODE
        OUTPUT_VARIABLE VERSION
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
    )

    if(NOT ERRCODE)
        if(VERSION MATCHES "^v?\([0-9]+\)\(\\.\([0-9]+\)\(\\.\([0-9]+\)\)?\)?")
            set(MAJOR_VERSION "${CMAKE_MATCH_1}")
            if(CMAKE_MATCH_COUNT GREATER 2)
                set(MINOR_VERSION "${CMAKE_MATCH_3}")
                if(CMAKE_MATCH_COUNT GREATER 4)
                    set(PATCH_VERSION "${CMAKE_MATCH_5}")
                endif()
            endif()
        endif()
    endif()

    execute_process(
        COMMAND ${GIT_EXECUTABLE} -C ${REPO} rev-parse HEAD
        OUTPUT_VARIABLE BUILD_COMMIT
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )

    execute_process(
        COMMAND ${GIT_EXECUTABLE} -C ${REPO} status --porcelain
        OUTPUT_VARIABLE REPO_STATUS
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
    )

    if ("${REPO_STATUS}" STREQUAL "")
        set(VERSION_CLEAN "true")
    endif()
endif()

set(VERSION_STRING "${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}")

# Process namespace
if (NOT "${NAMESPACE}" STREQUAL "")
    string(REGEX MATCHALL "[a-zA-Z_][a-zA-Z0-9_]*" MATCH "${NAMESPACE}")
    foreach(m ${MATCH})
        list(APPEND NAMESPACE_BEGIN "namespace ${m} {")
        list(APPEND NAMESPACE_END "}")
    endforeach()
    list(JOIN NAMESPACE_BEGIN "\n" NAMESPACE_BEGIN)
    list(JOIN NAMESPACE_END "\n" NAMESPACE_END)
endif()

configure_file("${SRC}" "${DST}" @ONLY)