"""MaxwellBloch

MaxwellBloch is a Python package for solving the coupled Maxwell-Bloch equations
describing the nonlinear propagation of near-resonant light through thermal
atomic vapours.
"""

import os 
import textwrap 
from setuptools import setup, find_packages 
import subprocess

DESCRIPTION = "A Python package for solving the Maxwell-Bloch equations."

LONG_DESCRIPTION = ("MaxwellBloch is a Python package for solving the coupled "
    "Maxwell-Bloch equations describing the nonlinear propagation of "
    "near-resonant light through thermal atomic vapours.")

def git_short_hash():
    """ Returns the short hash of the HEAD commit as a string. """
    try:
        return subprocess.check_output(['git', 'log', '-1',
            '--format=%h']).decode('UTF-8').strip()
    except subprocess.CalledProcessError:
        return None

def git_tag():
    """ Return the latest annotated tag on the HEAD commit as a string.

    Notes:
        For tags not annotated, we'd need to add the --tags flag.
    """
    try:
        return subprocess.check_output(
            ['git', 'describe', '--exact-match']).decode('UTF-8').strip()
    except subprocess.CalledProcessError:
        return None

def version():
    """ Get version from tag or commit short hash. 
    
    Use annotated tag if that exists. If not, use short hash.
    """

    if git_tag():
        version = git_tag()
    elif git_short_hash():
        version = git_short_hash()
    else:
        version = "no_version"
    return version

def write_version_module(version, version_path='maxwellbloch/version.py'):
    """ Write a version module with the current version."""
    # Remove if already exists
    if os.path.exists(version_path):
        os.remove(version_path)
    version_str = textwrap.dedent("""\
        # This file is generated by setup.py
        VERSION = '{!s}'
        """.format(version))
    f = open(version_path, 'w')
    try:
        f.write(version_str)
    finally:
        f.close()

version = version()
write_version_module(version=version)

setup(name='MaxwellBloch',
      version=version,
      description=DESCRIPTION,
      long_description=LONG_DESCRIPTION,
      url='http://github.com/tpogden/maxwellbloch',
      author='Thomas P Ogden',
      author_email='t@ogden.eu',
      license='MIT',
      packages=find_packages(),
      package_data={'maxwellbloch.tests': ['json/*.json']},
      install_requires=['qutip'],
      scripts=[
        'bin/mbsolve',
        'bin/obsolve',
        'bin/make-mp4-fixed-frame.py',
        'bin/make-mp4-fixed-frame-2-fields.py',
        'bin/make-gif-ffmpeg.sh'],
      zip_safe=False)
