#!/usr/bin/python

#
# Copyright 2011 Tom Klein.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys, subprocess, re

###############################################################################
# get the current version
###############################################################################
# determine the current git sequence number
gitHashListString = subprocess.Popen(["git", "rev-list", "HEAD"],
                                     stdout=subprocess.PIPE).communicate()[0]
gitCount = str(gitHashListString.count("\n"))

# and the latest git tag number (\d.\d.\d)
gitVersionBase = (
    subprocess.Popen(["git", "describe", "--tags", "--abbrev=0"],
                     stdout=subprocess.PIPE).communicate()[0].rstrip())
gitVersion = gitVersionBase + "." + gitCount

###############################################################################
# update the program's stored version number
###############################################################################
versionFilename = "main.cpp"
versionFile = open(versionFilename)
# (if a cpp file is too big for readlines to be reasonable, then something is
# wrong with the cpp file...)
fileLines = versionFile.readlines()
versionFile.close()

# match .*(.*).*// @GIT-VERSION, as in, for example,
# winManager.setVersion("1.0.0.63"); // @GIT-VERSION - don't touch this comment
setVersionRE = re.compile(r'^(.*\().*(\).*// @GIT-VERSION - don\'t touch this comment)')
for i in range(len(fileLines)):
    reMatch = setVersionRE.search(fileLines[i])
    if reMatch:
        print "Setting new version: " + gitVersion
        fileLines[i] = reMatch.group(1) + '"' + gitVersion + '"' + reMatch.group(2) + '\n'
        break

newVersionFile = open(versionFilename, 'w')
newVersionFile.writelines(fileLines)
newVersionFile.close()

print "Adding newly versioned " + versionFilename + " to this commit."
subprocess.Popen(["git", "add", versionFilename]);

# exit non-zero to abort the commit
#sys.exit(1)
