# Increment the build counter and write buildnumber.h.
#
# Run with `cmake -P` as a build step, so it fires on every build rather than
# once per configure. Item 167: the version alone cannot tell one build of an
# unreleased X.Y.Z from another, and the user hand-tests unreleased builds
# daily.
#
# Expects COUNTER_FILE and HEADER_FILE on the command line.
#
# The counter lives in the BUILD directory and is deliberately not tracked: a
# committed counter would conflict on every pull and leave the tree dirty
# after every build. A fresh build directory therefore restarts at 1, which is
# honest, since it is a different build tree.

if(EXISTS "${COUNTER_FILE}")
    file(READ "${COUNTER_FILE}" current)
    string(STRIP "${current}" current)
endif()

if(NOT current MATCHES "^[0-9]+$")
    set(current 0)
endif()

math(EXPR next "${current} + 1")
file(WRITE "${COUNTER_FILE}" "${next}\n")

# Written to a temporary and copied only if different, so a rebuild that
# changes nothing else does not force every translation unit including
# version.h to recompile... except that the number itself changes every time,
# so it always differs. That is the accepted cost of the feature: the few
# files that read the version are recompiled and relinked on every build.
file(WRITE "${HEADER_FILE}.tmp"
"// Generated by cmake/BuildNumber.cmake on every build. Do not edit, and do
// not commit: this file lives in the build directory.
#pragma once
#define QTMAILDIR_BUILD_NUMBER \"${next}\"
")
file(COPY_FILE "${HEADER_FILE}.tmp" "${HEADER_FILE}" ONLY_IF_DIFFERENT)
