#!/usr/bin/env/python
# coding=utf-8

import sys
import os 
import subprocess

here = os.path.join(os.path.abspath(os.path.dirname(__file__)),'tofu')

def updateversion(here=here):
    # Fetch version from git tags, and write to version.py
    # Also, when git is not available (PyPi package), use stored version.py
    version_py = os.path.join(here,"version.py")
    try:
        if sys.version[0]=='2':
            version_git = subprocess.check_output(["git","describe"]).rstrip()
        elif sys.version[0]=='3':
            version_git = subprocess.check_output(["git","describe"]).rstrip().decode()
        else:
            raise Exception("Wrong python version !")
    except:
        with open(version_py,'r') as fh:
            version_git = fh.read().strip().split("=")[-1].replace("'",'')
    version_git = version_git[1:] if version_git[0].lower()=='v' else version_git

    version_msg = "# Do not edit this file, pipeline versioning is governed by git tags !"
    with open(version_py,"w") as fh:
        fh.write((version_msg + os.linesep + '__version__=').replace('',"") + "'%s'" % version_git)
    return version_git




