#! /usr/bin/python2.4

import os
import re
import sys

try:
    __file__
except NameError:
    __file__ = sys.argv[0]

tools = os.path.dirname(os.path.abspath(__file__))
Doc = os.path.dirname(tools)
src = os.path.dirname(Doc)
patchlevel_h = os.path.join(src, "Include", "patchlevel.h")

# This won't pick out all #defines, but it will pick up the ones we
# care about.
rx = re.compile(r"\s*#define\s+([a-zA-Z][a-zA-Z_0-9]*)\s+([a-zA-Z_0-9]+)")

d = {}
f = open(patchlevel_h)
for line in f:
    m = rx.match(line)
    if m is not None:
        name, value = m.group(1, 2)
        d[name] = value
f.close()

release = "%s.%s" % (d["PY_MAJOR_VERSION"], d["PY_MINOR_VERSION"])
micro = int(d["PY_MICRO_VERSION"])
shortversion = release
if micro != 0:
    release += "." + str(micro)
level = d["PY_RELEASE_LEVEL"]

suffixes = {
    "PY_RELEASE_LEVEL_ALPHA": "a",
    "PY_RELEASE_LEVEL_BETA":  "b",
    "PY_RELEASE_LEVEL_GAMMA": "c",
    }

releaseinfo = ""
if level != "PY_RELEASE_LEVEL_FINAL":
    releaseinfo = suffixes[level] + str(int(d["PY_RELEASE_SERIAL"]))

def write_file(name, text):
    """Write text to a file if the file doesn't exist or if text
    differs from any existing content."""
    if os.path.exists(name):
        f = open(name, "r")
        s = f.read()
        f.close()
        if s == text:
            return
    f = open(name, "w")
    f.write(text)
    f.close()

patchlevel_tex = os.path.join(Doc, "commontex", "patchlevel.tex")

write_file(patchlevel_tex,
           "%% This file is generated by ../tools/getversioninfo;\n"
           "%% do not edit manually.\n"
           "\n"
           "\\release{%s}\n"
           "\\setreleaseinfo{%s}\n"
           "\\setshortversion{%s}\n"
           % (release, releaseinfo, shortversion))

print release + releaseinfo
