from __future__ import unicode_literals

import os
import subprocess

from pelican import signals


def app_version(generator):
    def minimal_env_cmd(cmd):
        # make minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v

        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        # version
        describe = minimal_env_cmd(["git", "describe", "--always"])
        git_revision = describe.strip().decode('ascii')
        # branch
        branch = minimal_env_cmd(["git", "branch"])
        git_branch = branch.strip().decode('ascii').replace('* ', '')
    except OSError:
        git_revision = "Unknown"
        git_branch = "Unknown"

    generator.context['CURRENT_VERSION'] = git_revision
    generator.context['CURRENT_BRANCH'] = git_branch


def register():
    signals.generator_init.connect(app_version)
