#!/usr/bin/env python
import os
import sys
import re
import subprocess

has_changes = 'la copie de travail est propre' not in str(subprocess.check_output(["git", "status"]).rstrip())
if has_changes:

	version_py = os.path.join(os.path.dirname(__file__), 'workon/version.py')

	version = re.search(r'__version__ = "([\d\.]+)"', open(version_py, 'r').read()).group(1)

	major, medium, minor = version.split(".")

	if sys.argv[1] == 'minor':
		minor = int(minor) + 1

	elif sys.argv[1] == 'medium':
		medium = int(medium) + 1
		minor = 0

	elif sys.argv[1] == 'major':
		major = int(major) + 1
		medium = 0
		minor = 0


	new_version = "{}.{}.{}".format(major, medium, minor)
	version_msg = "# Do not edit this file, pipeline versioning is governed by git tags" + os.linesep + "# following PEP 386"
	open(version_py, 'w').write(version_msg + os.linesep + '__version__ = "%s"' % new_version)


	subprocess.check_output(["git", "add", "."])
	subprocess.check_output(["git", "commit", "-am", '"autofix"'])
	subprocess.check_output(["git", "tag", "-a", new_version, '-m', '"autoversionning"'])