# This script walks through all *.py that are included in the binary
# package and replaces the build-specify timestamp and build path
# generated by Cheetah.  This makes the building of the package
# reproducible.  This script is intended to be called in the
# override_dh_auto_install rule.

import fileinput
import fnmatch
import os
import re
import sys
import time

from dateutil import parser

import debian.changelog as dch

with open("debian/changelog", "r", encoding="utf-8") as fid:
    ch = dch.Changelog(fid)
    dt = ch[0].date
    ts = time.mktime(parser.parse(dt).timetuple())

for dName, sdName, fList in os.walk("debian/xmds2"):
    for fileName in fList:
        if fnmatch.fnmatch(fileName, "*.py"):
            fname = os.path.join(dName, fileName)
            for line in fileinput.input(fname, inplace=True, encoding="utf-8"):
                outline = line
                if re.match("^__CHEETAH_srcLastModified__ = .*$", line):
                    outline = f"__CHEETAH_srcLastModified__ = '{dt}'\n"
                m = re.match("^__CHEETAH_src__ = '.*/(.*)'$", line)
                if m:
                    outline = f"__CHEETAH_src__ = '{m.group(1)}'\n"
                sys.stdout.write(outline)
