import os
import subprocess

from bento.core \
    import \
        PackageDescription

def generate_version_py(filename):
    pkg = PackageDescription.from_file("bento.info")

    FULL_VERSION = pkg.version
    if "dev" in FULL_VERSION:
        RELEASED = False
    else:
        RELEASED = True

    try:
        if os.path.exists(".git"):
            s = subprocess.Popen(["git", "rev-parse", "HEAD"],
                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            out = s.communicate()[0]
            GIT_REVISION = out.decode().strip()
        else:
            GIT_REVISION = ""
    except WindowsError:
        GIT_REVISION = ""

    cnt = """\
# This file was autogenerated
version = '%s'
git_revision = '%s'
"""
    cnt = cnt % (FULL_VERSION, GIT_REVISION)

    f = open(filename, "w")
    try:
        f.write(cnt)
    finally:
        f.close()

    return FULL_VERSION, GIT_REVISION
