import os
import subprocess
from setuptools import setup, find_packages


def apply_versioning():
    with open('.version', 'r') as v_file:
        version, *meta = [x.strip() for x in v_file.readlines() if x.strip()]

    # Got this from here
    # http://blogs.nopcode.org/brainstorm/2013/05/20/pragmatic-python-versioning-via-setuptools-and-git-tags/
    # 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(os.path.dirname(__file__), 'boardom/version.py')

    if meta[0] == 'no_git':
        full_version = version
    else:
        try:
            build = (
                subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])
                .rstrip()
                .decode("utf-8")
            )
        except:
            with open(version_py, 'r') as fh:
                build = open(version_py).read().strip().split('=')[-1].replace('"', '')

        full_version = version + '+' + build

    version_msg = "# Do not edit this file, pipeline versioning is governed by git tags"
    with open(version_py, 'w') as fh:
        fh.write(f'{version_msg}\n__version__ = "{full_version}"')
    return full_version


def read_readme():
    with open('README.md') as f:
        return f.read()


setup(
    name='boardom',
    version=apply_versioning(),
    description='Deep learning toolbox/framework.',
    long_description=read_readme(),
    url='https://github.com/dmarnerides/boardom',
    license='BSD',
    author='Demetris Marnerides',
    author_email='dmarnerides@gmail.com',
    packages=find_packages(exclude=['tests']),
    package_data={
        'boardom.board': ['dist/*.*'],
        'boardom.matlab_engine': ['*.m'],
        'boardom.assets': ['*'],
    },
    entry_points={
        'console_scripts': [
            'bd-plot=boardom.plot.csvplot:plot_csv',
            'boardom=boardom.board.server:run_server',
        ]
    },
    zip_safe=False,
)
