from subprocess import Popen, PIPE, check_output
from tempfile import mkstemp
from shutil import move
from os import remove, close
import re, subprocess, sys

branch = check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).rstrip().decode("utf-8")
shorthash = check_output(["git", "log", "--pretty=format:%h", "-n 1"]).rstrip().decode("utf-8")
revcount = int(check_output(["git", "rev-list", "--count", "HEAD"]))
tag = check_output(["git", "describe", "--tags", "--abbrev=0"]).rstrip().decode("utf-8").split('-',1)[0]
config = sys.argv[2].lower()

version = "%s.%d (%s-%s-%s)" % (tag, revcount, shorthash, branch, config)
version_number = "%s.%d" % (tag, revcount)

version_parts = version_number.split('.')

print("Compiling version: %s" % version)

file_path = sys.argv[1];
#Create temp file
fh, abs_path = mkstemp()
regex = re.compile(r'(.*<Identity[^>]+Version=)("\d+\.\d+\.\d+\.\d+")')
with open(abs_path,'w') as new_file:
    with open(file_path) as old_file:
        for line in old_file:
            new_line = regex.sub(r'\1"%s.0"' % tag, line)
            new_file.write(new_line)
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)

exit(0)
