#!/usr/bin/env python3

import fileinput

# the version of the release
with open("version.txt") as f: version = f.read()

def getVersionTuple(v):
    return tuple(map(int, (v.split("."))))

version_major = str(getVersionTuple(version)[0])
version_minor = str(getVersionTuple(version)[1])
version_patch = str(getVersionTuple(version)[2])

# update version in the header file
print("updating the version in the header file")
doctest_contents = ""
for line in fileinput.input(["../doctest/parts/public/version.h"]):
    if line.startswith("#define DOCTEST_VERSION_MAJOR "):
        doctest_contents += "#define DOCTEST_VERSION_MAJOR " + version_major + "\n"
    elif line.startswith("#define DOCTEST_VERSION_MINOR "):
        doctest_contents += "#define DOCTEST_VERSION_MINOR " + version_minor + "\n"
    elif line.startswith("#define DOCTEST_VERSION_PATCH "):
        doctest_contents += "#define DOCTEST_VERSION_PATCH " + version_patch + "\n"
    else:
        doctest_contents += line

readme = open("../doctest/parts/public/version.h", "w", encoding="utf-8", newline="\n")
readme.write(doctest_contents)
readme.close()

# update meson file with version
print("updating the meson file")
meson_contents = ""
for line in fileinput.input(["../meson.build"]):
    if line.startswith("project('doctest'"):
        meson_contents += "project('doctest', ['cpp'], version: '" + version + "')\n"
    else:
        meson_contents += line

meson = open("../meson.build", "w", encoding="utf-8", newline="\n")
meson.write(meson_contents)
meson.close()


# update MODULE.bazel file with version
print("updating the MODULE.bazel file")
bzlmod_contents = ""
for line in fileinput.input(["../MODULE.bazel"]):
    if line.startswith("    version = "):
        bzlmod_contents += "    version = \"" + version + "\",\n"
    else:
        bzlmod_contents += line

bzlmod = open("../MODULE.bazel", "w")
bzlmod.write(bzlmod_contents)
bzlmod.close()
