# vim: set ts=2 sw=2 tw=99 noet ft=python: 
import os
import re
import subprocess
from ambuild.cache import Cache
import ambuild.command as command

#Quickly try to ascertain the current repository revision
def GetVersion():
        p = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
        (stdout, stderr) = p.communicate()
        stdout = stdout.decode('UTF-8')
        return stdout.rstrip('\r\n')

def PerformReversioning():
	cset = GetVersion()
	cacheFile = os.path.join(AMBuild.outputFolder, '.ambuild', 'hgcache')
	cache = Cache(cacheFile)
	if os.path.isfile(cacheFile):
		cache.LoadCache()
		if cache.HasVariable('cset') and cache['cset'] == cset:
			return False
	cache.CacheVariable('cset', cset)

	productFile = open(os.path.join(AMBuild.sourceFolder, 'product.version'), 'r')
	productContents = productFile.read()
	productFile.close()
	m = re.match('(\d+)\.(\d+)\.(\d+)(.*)', productContents)
	if m == None:
		raise Exception('Could not detremine product version')
	major, minor, release, tag = m.groups()

	incFolder = os.path.join(AMBuild.sourceFolder, 'extension')
	incFile = open(os.path.join(incFolder, 'version_auto.h'), 'w')
	incFile.write("""
#ifndef _AUTO_VERSION_INFORMATION_H_
#define _AUTO_VERSION_INFORMATION_H_

#define SM_BUILD_TAG	 	\"{0}\"
#define SM_BUILD_UNIQUEID	\"{1}\"
#define SM_VERSION			\"{2}.{3}.{4}\"
#define SM_FULL_VERSION		SM_VERSION SM_BUILD_TAG "+" SM_BUILD_UNIQUEID
#define SM_FILE_VERSION		{5},{6},{7},0

#endif /* _AUTO_VERSION_INFORMATION_H_ */

""".format(tag, cset, major, minor, release, major, minor, release))
	incFile.close()
	cache.WriteCache()

PerformReversioning()


