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]
if len(sys.argv) < 2:
    print("pre-build.py failed")
    exit(0)
    
config = sys.argv[1].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)

version_gen_h = '// AUTO GENERATED FILE - DON\'T MODIFY\n'
version_gen_h += '#define PP_VERSION_NUMBER_STRING "%s"\n' % version_number
version_gen_h += '#define PP_VERSION_STRING "%s"\n' % version
version_gen_h += '#define PP_VERSION_MAJOR %s\n' % version_parts[0]
version_gen_h += '#define PP_VERSION_MINOR %s\n' % version_parts[1]
version_gen_h += '#define PP_VERSION_FIX %s\n' % version_parts[2]
version_gen_h += '#define PP_VERSION_BUILD %s\n' % version_parts[3]
version_gen_h += '#define PP_RC_BUILD_VERSION %s\n' % version_number.replace('.',',')
version_gen_h += '#define PP_RC_BUILD_VERSION_STRING "%s\\0"\n' % version
version_gen_h += '#define PP_RC_PRODUCT_VERSION %s,0\n' % tag.replace('.',',')
version_gen_h += '#define PP_RC_PRODUCT_VERSION_STRING "%s\\0"\n' % tag
f = open("src/version.gen.h", "w")
f.write(version_gen_h)


"""
file_path = "Setup\\Product.wxs";
#Create temp file
fh, abs_path = mkstemp()
regex = re.compile(r'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('Version="%s"' % version, line)
            new_file.write(new_line)
close(fh)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
"""


exit(0)
