# Pure cmake script to write out cmake_commit.c and cmake_version.but

set(DEFAULT_COMMIT "unavailable")
set(commit "${DEFAULT_COMMIT}")

set(TOPLEVEL_SOURCE_DIR ${CMAKE_SOURCE_DIR})

execute_process(
  COMMAND ${GIT_EXECUTABLE} rev-parse --show-cdup
  OUTPUT_VARIABLE path_to_top
  ERROR_VARIABLE stderr
  RESULT_VARIABLE status)
string(REGEX REPLACE "\n$" "" path_to_top "${path_to_top}")

# If we're at the top of a git repository, --show-cdup will print the
# empty string (followed by a newline) and return success. If we're
# lower down, it will return a sequence of "../../" that leads to the
# top; if we're higher up it will fail with an error.
if(status EQUAL 0 AND path_to_top STREQUAL "")
  execute_process(
    COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
    OUTPUT_VARIABLE git_commit
    ERROR_VARIABLE stderr
    RESULT_VARIABLE status)
  if(status EQUAL 0)
    string(REGEX REPLACE "\n$" "" commit "${git_commit}")
  else()
    if(commit STREQUAL "unavailable")
      message("Unable to determine git commit: 'git rev-parse HEAD' returned status ${status} and error output:\n${stderr}\n")
    endif()
  endif()
else()
  if(commit STREQUAL "unavailable")
    message("Unable to determine git commit: top-level source dir ${CMAKE_SOURCE_DIR} is not the root of a repository")
  endif()
endif()

if(OUTPUT_TYPE STREQUAL header)
  file(WRITE "${OUTPUT_FILE}" "\
/*
 * cmake_commit.c - string literal giving the source git commit, if known.
 *
 * Generated by cmake/gitcommit.cmake.
 */

#include \"putty.h\"
const char commitid[] = \"${commit}\";
")
elseif(OUTPUT_TYPE STREQUAL halibut)
  if(commit STREQUAL "unavailable")
    file(WRITE "${OUTPUT_FILE}" "\
\\versionid no version information available
")
  else()
    file(WRITE "${OUTPUT_FILE}" "\
\\versionid built from git commit ${commit}
")
  endif()
else()
  message(FATAL_ERROR "Set OUTPUT_TYPE when running this script")
endif()