#!/usr/bin/env python

import sys
import subprocess
import os
from os import path
import re

version = {}

header = """/* This file is automatically generated by {0}!
 * Do not edit manually, any manual change will be overwritten.
 */
"""


def extract_information_from_git():
    revision = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip()

    version['revision'] = revision[0:12]
    version['irevision0'] = "0x" + revision[0:8]
    version['irevision1'] = "0x" + revision[8:12]

    try:
        identify = subprocess.check_output(
            ["git", "describe", "--abbrev=12", "--tags", "HEAD"])
        identify = identify.split('-')

        if len(identify) > 2:
            version['local_revision'] = identify[len(identify) - 2]
        else:
            version['local_revision'] = '0'

        version['tag'] = identify[0]
        for x in range(1, len(identify) - 2):
            version['tag'] += '-'
            version['tag'] += identify[x]
    except subprocess.CalledProcessError:
        # We are running from a shallow tree, CI build?
        # Fill up default values, this will not happen when releasing.
        version['local_revision'] = '0'
        version['tag'] = "ci-build"

    version['tag'] = version['tag'].strip()

    if version['local_revision'] != '0':
        version['tag'] = version['tag'] + '-' + version['local_revision']

    branch = subprocess.check_output(
        ["git", "rev-parse", "--abbrev-ref", "HEAD"]).strip()
    version['branch'] = branch

    subprocess.call(["git", "update-index", "-q", "--refresh"])
    changes = subprocess.check_output(
        ["git", "diff-index", "--name-only", "HEAD", "--"]).strip()
    if len(changes):
        version['modified'] = 'true'
    else:
        version['modified'] = 'false'


def extract_information_from_folder_name():
    sourcefolder = path.basename(path.abspath(path.dirname(__file__) + '/..'))
    match = re.match(".*(20[0-9][0-9]\\.[0-9][0-9]?(\\.[0-9][0-9]?)?)$",
                     sourcefolder)

    version['revision'] = 'NA'
    version['irevision0'] = "0x" + '0'
    version['irevision1'] = "0x" + '0'
    version['local_revision'] = 'NA'
    version['branch'] = 'NA'
    version['modified'] = 'true'

    if match is not None:
        version['tag'] = match.group(1)
    else:
        version['tag'] = 'NA'


def print_version():
    status = "\033[1;32mCLEAN\033[m"
    if (version['modified'] == 'true'):
        status = "\033[1;31mMODIFIED\033[m"

    print("Build {local_revision}:{revision} ({tag}) {}".format(status,
                                                                **version))
    print("Version extracted from {source}".format(**version))

if __name__ == "__main__":
    version_source = ""
    if os.path.isdir(".git"):
        version['source'] = "git"
        extract_information_from_git()
    else:
        version['source'] = "folder name"
        extract_information_from_folder_name()

    if len(sys.argv) == 2 and sys.argv[1] == "--print-version":
        print_version()
        sys.exit(0)

    if len(sys.argv) < 3:
        print("Usage:")
        print("  {0} <infile> <outfile>".format(sys.argv[0]))
        sys.exit(1)


    # Apply information to the file template
    infile = open(sys.argv[1], 'r')
    outfile = open(sys.argv[2], 'w')

    outfile.write(header.format(sys.argv[0], sys.argv[1]))
    outfile.write(infile.read().format(**version))

    infile.close()
    outfile.close()
