#!/usr/bin/env python

import os
import sys
import subprocess
from setuptools import setup, Extension
import numpy


# Change version number here, not in axographio/version.py, which is generated
# by this script. Try to follow recommended versioning guidelines at semver.org.
MAJOR       = 0     # increment for backwards-incompatible changes
MINOR       = 3     # increment for backwards-compatible feature additions
MICRO       = 2     # increment for backwards-compatible bug fixes
IS_RELEASED = True  # determines whether version will be marked as development
VERSION     = '%d.%d.%d' % (MAJOR, MINOR, MICRO)


# This function may be used below to query git for a revision number.
def _minimal_ext_cmd(cmd):
    """Run an external command and return the result."""
    # construct minimal environment
    env = {}
    for k in ['SYSTEMROOT', 'PATH', 'HOME']:
        v = os.environ.get(k)
        if v is not None:
            env[k] = v
    # LANGUAGE is used on win32
    env['LANGUAGE'] = 'C'
    env['LANG'] = 'C'
    env['LC_ALL'] = 'C'
    out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0]
    return out


# Try to fetch the git revision number from the .git directory if it exists.
if os.path.exists(".git"):
    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "unknown"
# If the .git directory is absent (perhaps because this is a source distro),
# try to fetch the rev number from axographio/version.py where it may have been
# stored during packaging.
elif os.path.exists("axographio/version.py"):
    try:
        v = {}
        with open("axographio/version.py", "r") as f:
            exec(f.read(), v)
        GIT_REVISION = v['git_revision']
    except ImportError:
        raise ImportError("Unable to import git_revision. Try removing " \
                          "axographio/version.py and the build directory " \
                          "before building.")
else:
    GIT_REVISION = "unknown"


# If this is not a release version, mark it as a development build/distro and
# tag it with the git revision number.
if not IS_RELEASED:
    VERSION += '.dev0+' + GIT_REVISION[:7]


# Write the version string to a file that will be included with the
# build/distro. This makes the string accessible to the package via
# axographio.__version__. The git revision is also written in case a source
# distro is being built, so that it can be fetched later during installation.
with open("axographio/version.py", "w") as f:
    try:
        f.write("\"\"\"THIS FILE WAS GENERATED BY SETUP.PY DURING BUILDING/PACKAGING\"\"\"\n")
        f.write("version = '%s'\n" % VERSION)
        f.write("git_revision = '%s'\n" % GIT_REVISION)
    finally:
        f.close()


# Read in the README to serve as the long_description, which will be presented
# on pypi.org as the project description.
with open("README.rst", "r") as f:
    README = f.read()


setup(
    name = "axographio",
    version = VERSION,
    setup_requires   = ['numpy', 'cython>=0.19'],   # needed to build axographio
    install_requires = ['numpy'],                   # needed to run axographio
    packages = ['axographio', 'axographio.tests'],
    ext_modules = [
        Extension('axographio.extension', [
            'axographio/extension.pyx',
            'axographio/include/axograph_readwrite/fileUtils.cpp',
            'axographio/include/axograph_readwrite/byteswap.cpp',
            'axographio/include/axograph_readwrite/stringUtils.cpp',
            'axographio/include/axograph_readwrite/AxoGraph_ReadWrite.cpp'],
            language='c++', include_dirs=[numpy.get_include()],
            define_macros=[('NO_CARBON',1)]
            )
        ],
    test_suite = 'axographio.tests.test_axographio.test_suite',
    package_data = {'axographio.tests': [
        '../include/axograph_readwrite/AxoGraph Digitized File',
        '../include/axograph_readwrite/AxoGraph Graph File',
        '../include/axograph_readwrite/AxoGraph X File.axgx'
        ]},
    # metatdata
    author = "Kendrick Shaw, Jeffrey Gill",
    author_email = "kms15@case.edu, jeffrey.p.gill@gmail.com",
    maintainer = "Jeffrey Gill",
    maintainer_email = "jeffrey.p.gill@gmail.com",
    license = "BSD License",
    keywords = ["physiology","electrophysiology","axograph"],
    url = "https://github.com/CWRUChielLab/axographio",
    description = "A Python package for reading and writing AxoGraph data files",
    long_description = README,
    classifiers = [
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: BSD License",
        "Topic :: Scientific/Engineering :: Bio-Informatics"
        ]
    )
