#!/usr/bin/python
import os
import re
import subprocess as sp


def up_version(ver, idx):
    ver[idx] += 1
    return ver[:idx + 1] + [0] * (3 - idx)

commands = {
    '#vtwe++': lambda ver: up_version(ver, 3),
    '#vpat++': lambda ver: up_version(ver, 2),
    '#vmin++': lambda ver: up_version(ver, 1),
    '#vmaj++': lambda ver: up_version(ver, 0),
}

message = sp.check_output(['git', 'log', '-1', 'HEAD', '--pretty=format:%s'])

get_new_version = None
for cmd, func in commands.items():
    if message.find(cmd) != -1:
        get_new_version = func
        break
if get_new_version is None:
    exit()

root_dir = sp.check_output(['git', 'rev-parse', '--show-toplevel']).strip()
cmake_path = os.path.join(root_dir, 'CMakeLists.txt')

with open(cmake_path) as cmake_file:
    cmake_lines = cmake_file.readlines()

version_str = ''
project_line_idx = 0

for idx, line in enumerate(cmake_lines):
    project_found = re.search('^project\(.*\)', line)
    if project_found is None:
        continue
    project_line = project_found.group(0)
    version_found = re.search('VERSION \d+.\d+.\d+.\d+', project_line)
    if version_found is None:
        continue
    version_str = version_found.group(0).replace('VERSION ', '')
    project_line_idx = idx
    break

if version_str:
    version = [int(v) for v in version_str.split('.')]
    new_version = [str(v) for v in get_new_version(version)]
    cmake_lines[project_line_idx].replace(version_str, '.'.join(new_version))

with open(cmake_path, 'w') as cmake_file:
   cmake_file.write(''.join(cmake_lines))


add post-commit.py