# GenerateVersion.cmake — run at build time via add_custom_target
# Writes a C++ header and a CMake include file derived from `git describe`.
#
# Expected -D inputs:
#   GIT_EXECUTABLE   — path to git
#   SOURCE_DIR       — repo root (for git describe)
#   OUTPUT_DIR       — directory for generated files

find_package(Git QUIET)

set(VERSION_STR "0.0.0-unknown")

if(GIT_EXECUTABLE)
    execute_process(
        COMMAND "${GIT_EXECUTABLE}" describe --tags --always --dirty
        WORKING_DIRECTORY "${SOURCE_DIR}"
        OUTPUT_VARIABLE GIT_DESCRIBE
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET
        RESULT_VARIABLE GIT_RESULT
    )
    if(GIT_RESULT EQUAL 0 AND GIT_DESCRIBE)
        set(VERSION_STR "${GIT_DESCRIBE}")
    endif()
endif()

# Parse numeric version components (e.g. v2.0.0-rc4-60-geac7c2f0 → 2, 0, 0)
string(REGEX MATCH "^v?([0-9]+)\\.([0-9]+)\\.([0-9]+)" _match "${VERSION_STR}")
if(_match)
    set(VERSION_MAJOR "${CMAKE_MATCH_1}")
    set(VERSION_MINOR "${CMAKE_MATCH_2}")
    set(VERSION_PATCH "${CMAKE_MATCH_3}")
else()
    set(VERSION_MAJOR 0)
    set(VERSION_MINOR 0)
    set(VERSION_PATCH 0)
endif()

# Helper: write file only when content actually changed, so downstream build
# steps (compiler, resource compiler, linker) don't rebuild unnecessarily.
function(write_if_changed path content)
    if(EXISTS "${path}")
        file(READ "${path}" old)
        if("${old}" STREQUAL "${content}")
            return()
        endif()
    endif()
    file(WRITE "${path}" "${content}")
endfunction()

# 1) C++ header — consumed via #include "imager_version.h"
set(HEADER_CONTENT "\
#pragma once
#define IMAGER_VERSION_STR \"${VERSION_STR}\"
")
write_if_changed("${OUTPUT_DIR}/imager_version.h" "${HEADER_CONTENT}")

# 2) CMake include file — consumed by ConfigureVersionedFile.cmake at build
#    time so that platform templates (.rc.in, .plist.in, etc.) get the fresh
#    version without a re-configure.
set(CMAKE_CONTENT "\
# Auto-generated by GenerateVersion.cmake — do not edit
set(IMAGER_VERSION_STR \"${VERSION_STR}\")
set(IMAGER_VERSION_MAJOR ${VERSION_MAJOR})
set(IMAGER_VERSION_MINOR ${VERSION_MINOR})
set(IMAGER_VERSION_PATCH ${VERSION_PATCH})
")
write_if_changed("${OUTPUT_DIR}/imager_version_vars.cmake" "${CMAKE_CONTENT}")

message(STATUS "Build-time version: ${VERSION_STR}")
