cmake_minimum_required(VERSION 3.22)

set(ROOT_DIR "" CACHE STRING "ChromaFlock source root")
set(OUT_DIR "" CACHE STRING "Output directory for generated header")

execute_process(COMMAND git rev-parse --short HEAD
    WORKING_DIRECTORY "${ROOT_DIR}"
    OUTPUT_VARIABLE GIT_HASH
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_QUIET)
if(NOT GIT_HASH)
    set(GIT_HASH "unknown")
endif()

execute_process(COMMAND git rev-parse --abbrev-ref HEAD
    WORKING_DIRECTORY "${ROOT_DIR}"
    OUTPUT_VARIABLE GIT_BRANCH
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_QUIET)
if(NOT GIT_BRANCH OR GIT_BRANCH STREQUAL "HEAD")
    execute_process(COMMAND git describe --tags --always
        WORKING_DIRECTORY "${ROOT_DIR}"
        OUTPUT_VARIABLE GIT_BRANCH
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET)
endif()
if(NOT GIT_BRANCH)
    set(GIT_BRANCH "unknown")
endif()

execute_process(COMMAND git status --porcelain
    WORKING_DIRECTORY "${ROOT_DIR}"
    OUTPUT_VARIABLE GIT_STATUS
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_QUIET)
if(GIT_STATUS STREQUAL "")
    set(GIT_DIRTY 0)
else()
    set(GIT_DIRTY 1)
endif()

set(CHROMAFLOCK_GIT_HASH "${GIT_HASH}")
set(CHROMAFLOCK_GIT_BRANCH "${GIT_BRANCH}")
set(CHROMAFLOCK_GIT_DIRTY ${GIT_DIRTY})

configure_file("${ROOT_DIR}/Source/BuildInfo.h.in"
               "${OUT_DIR}/BuildInfo.h" @ONLY)
