#!/usr/bin/env python
import json
import sys
import os
import re
import subprocess

# Import("env")
# print("mkversionh: env: ", env.Dump(), file=sys.stderr)

VERBOSE=False

DEFINE_PAT = re.compile(r"^#define\s+(?P<name>\w+)\s+(?P<value>.*)\s+$")


class VersionFile:
    def __init__(self, includeFile):
        self.includeFile = includeFile
        self.defines = {}
        self.changed = False
        if VERBOSE: print(f"mkversionh: loading {self.includeFile}", file=sys.stderr)
        for line in open(self.includeFile):
            match = DEFINE_PAT.match(line)
            if match:
                self.define(match.group("name"), match.group("value"))

    def define(self, name, value):
        if self.defines.get(name, None) == value:
            if VERBOSE: print(f"mkversionh: already set: {name}={value}", file=sys.stderr)
            return
        if VERBOSE: print(f"mkversionh: {name}={value}", file=sys.stderr)
        self.defines[name] = value
        self.changed = True

    def save(self):
        fp = open(self.includeFile, "w")
        for name, value in list(self.defines.items()):
            fp.write("#define %s %s\n" % (name, value))
        if VERBOSE: print(f"mkversionh: saved {self.includeFile}", file=sys.stderr)

    def get(self, key, default=None):
        return self.defines.get(key, default)


def main():
    try:
        baseDir = os.path.dirname(__file__)
    except NameError:
        baseDir = os.getcwd()
    while not os.path.exists(os.path.join(baseDir, "library.json")):
        newBaseDir = os.path.dirname(baseDir)
        if newBaseDir == baseDir:
            break
        baseDir = newBaseDir
    libraryConfig = os.path.join(baseDir, "library.json")
    version = os.path.join(baseDir, "src", "iotsaVersion.h")
    versionpy = os.path.join(baseDir, "extras", "python", "iotsa", "version.py")
    if not os.path.exists(libraryConfig) or not os.path.exists(version):
        print(f"mkversionh: Cannot find config files {libraryConfig} and {version}. Must be run from iotsa source tree.", file=sys.stderr)
        sys.exit(1)

    vf = VersionFile(version)

    libraryData = json.load(open(libraryConfig))
    if "version" in libraryData:
        vf.define("IOTSA_VERSION", '"' + libraryData["version"] + '"')

    cmd = subprocess.Popen(
        "git rev-parse --short HEAD",
        shell=True,
        cwd=baseDir,
        stdout=subprocess.PIPE,
        universal_newlines=True,
    )
    commit = cmd.stdout.read().strip()
    cmd2 = subprocess.run(
        "git diff --quiet ':!src/iotsaVersion.h' ':!extras/python/iotsa/version.py'",
        shell=True,
        cwd=baseDir,
    )
    if cmd2.returncode == 1:
        commit = commit + "-dirty"
    if commit:
        vf.define("IOTSA_COMMIT", '"' + commit + '"')
    else:
        if VERBOSE: print("mkversionh: cannot git rev-parse to get version information", file=sys.stderr)
    shortVersion = vf.get("IOTSA_VERSION", '"unknown""')
    fullVersion = shortVersion
    commit = vf.get("IOTSA_COMMIT")
    if commit:
        fullVersion = '"' + eval(fullVersion) + '+' + eval(commit) + '"'
    vf.define("IOTSA_FULL_VERSION", fullVersion)
    if vf.changed:
        vf.save()
    # Generate Python version file too
    PyNewVersion = f'__version__ = {fullVersion}\n__shortversion__ = {shortVersion}\n'
    PyOldVersion = open(versionpy).read()
    if PyNewVersion != PyOldVersion:
        open(versionpy, "w").write(PyNewVersion)

main()

@@ -2274,229 +2274,208 @@
     
-cmd = subprocess.Popen(%0A        %22git rev-parse --short HEAD%22,%0A        shell=True,%0A        cwd=baseDir,%0A        stdout=subprocess.PIPE,%0A        universal_newlines=True,%0A    )%0A    commit = cmd.stdout.read().strip()%0A
+if 'IOTSA_FULL_VERSION' in os.environ:%0A        fullVersion = os.environ%5B'IOTSA_FULL_VERSION'%5D%0A        if not '%22' in fullVersion:%0A            fullVersion = '%22' + fullVersion + '%22'%0A    else:%0A    
     cmd
-2
  = s
@@ -2488,13 +2488,19 @@
 ess.
-run(%0A
+Popen(%0A    
     
@@ -2513,76 +2513,27 @@
 it d
-iff --quiet ':!src/iotsaVersion.h' ':!extras/python/iotsa/version.py
+escribe --match 'v*
 '%22,%0A
@@ -2540,16 +2540,20 @@
         
+    
 shell=Tr
@@ -2556,16 +2556,20 @@
 l=True,%0A
+    
         
@@ -2589,470 +2589,250 @@
     
-)%0A
     
-if cmd2.returncode == 1:%0A        commit = commit + %22-dirty%22%0A    if commit:%0A        vf.define(%22IOTSA_COMMIT%22, '%22' + commit + '%22')%0A    else:%0A        if VERBOSE: print(%22mkversionh: cannot git rev-parse to get version information%22, file=sys.stderr)%0A    shortVersion = vf.get(%22IOTSA_VERSION%22, '%22unknown%22%22')%0A    fullVersion = shortVersion%0A    commit = vf.get(%22IOTSA_COMMIT%22)%0A    if commit:%0A        fullVersion = '%22' + eval(fullVersion) + '+' + eval(commit) + '%22'
+    stdout=subprocess.PIPE,%0A            universal_newlines=True,%0A        )%0A        fullVersion = cmd.stdout.read().strip()%0A    shortVersion = vf.get(%22IOTSA_VERSION%22, '%22unknown%22%22')%0A    if not fullVersion:%0A        fullVersion = shortVersion
 %0A   

Allow overriding version with environment variable