#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst

import glob
import os
import sys
from subprocess import check_output, CalledProcessError

try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser

# Get some values from the setup.cfg
conf = ConfigParser()
conf.read(['setup.cfg'])
metadata = dict(conf.items('metadata'))

PACKAGENAME = metadata.get('package_name', 'packagename')
DESCRIPTION = metadata.get('description', 'Astropy Package Template')
AUTHOR = metadata.get('author', 'Astropy Developers')
AUTHOR_EMAIL = metadata.get('author_email', '')
LICENSE = metadata.get('license', 'unknown')
URL = metadata.get('url', 'http://astropy.org')
__minimum_python_version__ = metadata.get("minimum_python_version", "2.7")

# Enforce Python version check - this is the same check as in __init__.py but
# this one has to happen before importing ah_bootstrap.
if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))):
    sys.stderr.write("ERROR: packagename requires Python {} or later\n".format(__minimum_python_version__))
    sys.exit(1)

# Import ah_bootstrap after the python version validation

import ah_bootstrap
from setuptools import setup

# A dirty hack to get around some early import/configurations ambiguities
if sys.version_info[0] >= 3:
    import builtins
else:
    import __builtin__ as builtins
builtins._ASTROPY_SETUP_ = True

from astropy_helpers.setup_helpers import (register_commands, get_debug_option,
                                           get_package_info,
                                           get_distutils_build_option)
from astropy_helpers.git_helpers import get_git_devstr
from astropy_helpers.version_helpers import generate_version_py

# order of priority for long_description:
#   (1) set in setup.cfg,
#   (2) load LONG_DESCRIPTION.rst,
#   (3) load README.rst,
#   (4) package docstring
readme_glob = 'README*'
_cfg_long_description = metadata.get('long_description', '')
if _cfg_long_description:
    LONG_DESCRIPTION = _cfg_long_description

elif os.path.exists('LONG_DESCRIPTION.rst'):
    with open('LONG_DESCRIPTION.rst') as f:
        LONG_DESCRIPTION = f.read()

elif len(glob.glob(readme_glob)) > 0:
    with open(glob.glob(readme_glob)[0]) as f:
        LONG_DESCRIPTION = f.read()

else:
    # Get the long description from the package's docstring
    __import__(PACKAGENAME)
    package = sys.modules[PACKAGENAME]
    LONG_DESCRIPTION = package.__doc__

# Store the package name in a built-in variable so it's easy
# to get from other parts of the setup infrastructure
builtins._ASTROPY_PACKAGE_NAME_ = PACKAGENAME

# VERSION should be PEP440 compatible (http://www.python.org/dev/peps/pep-0440)
VERSION = metadata.get('version', '0.0.dev')

# Indicates if this version is a release version
RELEASE = 'dev' not in VERSION

if not RELEASE:
    VERSION += get_git_devstr(False)

# Populate the dict of setup command overrides; this should be done before
# invoking any other functionality from distutils since it can potentially
# modify distutils' behavior.
cmdclassd = register_commands(PACKAGENAME, VERSION, RELEASE)

# Freeze build information in version.py
generate_version_py(PACKAGENAME, VERSION, RELEASE,
                    get_debug_option(PACKAGENAME))


# Get configuration information from all of the various subpackages.
# See the docstring for setup_helpers.update_package_files for more
# details.
package_info = get_package_info()

# Add the project-global data
package_info['package_data'].setdefault(PACKAGENAME, [])

# Include all .c files, recursively, including those generated by
# Cython, since we can not do this in MANIFEST.in with a "dynamic"
# directory name.
c_files = []
for root, dirs, files in os.walk(PACKAGENAME):
    for filename in files:
        if filename.endswith('.c'):
            c_files.append(
                os.path.join(
                    os.path.relpath(root, PACKAGENAME), filename))
package_info['package_data'][PACKAGENAME].extend(c_files)

# ----------------------------------------------------------------------------
# GSL support
#
extra_compile_macros_file = 'gala/extra_compile_macros.h'

# Note: on RTD, they now support conda environments, but don't activate the
# conda environment that gets created, and so the C stuff installed with GSL
# aren't picked up. This is my attempt to hack around that!
on_rtd = os.environ.get('READTHEDOCS') == 'True'
if on_rtd:
    PATH = '/home/docs/checkouts/readthedocs.org/user_builds/gala-astro/conda/latest/bin/'
    env = os.environ.copy()
    env['PATH'] = env.get('PATH', "") + ":" + PATH
else:
    env = None

# First, see if the user wants to install without GSL:
nogsl = get_distutils_build_option('nogsl')

# Auto-detect whether GSL is installed
if not nogsl or nogsl is None: # GSL support enabled
    cmd = ['gsl-config', '--version']
    try:
        gsl_version = check_output(cmd, env=env)
    except (OSError, CalledProcessError):
        gsl_version = None
    else:
        gsl_version = gsl_version.decode('utf-8').strip().split('.')

else:
    gsl_version = None

# If the hacky macros file already exists, read from that what to do.
# This means people experimenting might need to run "git clean" to remove all
# temp. build products if they want to switch between installing with GSL and
# no GSL support.
if os.path.exists(extra_compile_macros_file):
    with open(extra_compile_macros_file, "r") as f:
        line = f.read().strip()

    if line.endswith('0'):
        gsl_version = None
        nogsl = True

print()
_see_msg = ("See the gala documentation 'installation' page for more "
            "information about GSL support and installing GSL: "
            "http://gala.adrian.pw/en/latest/install.html")
if gsl_version is None:
    if nogsl:
        print('Installing without GSL support.')
    else:
        print('GSL not found: installing without GSL support. ' + _see_msg)

elif gsl_version < ['1', '14']:
    gsl_version = None
    print('Warning: GSL version ({0}) is below the minimum required version '
          '(1.16). Installing without GSL support. '
          .format('.'.join(gsl_version)) + _see_msg)

else:
    print("GSL version {0} found: installing with GSL support"
          .format('.'.join(gsl_version)))

    # Now get the gsl install location
    cmd = ['gsl-config', '--prefix']
    try:
        gsl_prefix = check_output(cmd, encoding='utf-8').strip()
    except:
        gsl_prefix = str(check_output(cmd)).strip()

print()

extensions = package_info['ext_modules']
for ext in extensions:
    if 'potential.potential' in ext.name or 'scf' in ext.name:
        if gsl_version is not None:
            if 'gsl' not in ext.libraries:
                ext.libraries.append('gsl')
                ext.library_dirs.append(os.path.join(gsl_prefix, 'lib'))
                ext.include_dirs.append(os.path.join(gsl_prefix, 'include'))

            if 'gslcblas' not in ext.libraries:
                ext.libraries.append('gslcblas')

with open(extra_compile_macros_file, 'w') as f:
    if gsl_version is not None:
        f.writelines(['#define USE_GSL 1'])
    else:
        f.writelines(['#define USE_GSL 0'])

# setup(name=PACKAGENAME,
setup(name='astro-gala',
      version=VERSION,
      description=DESCRIPTION,
      install_requires=[s.strip() for s in metadata.get('install_requires', 'astropy').split(',')],
      author=AUTHOR,
      author_email=AUTHOR_EMAIL,
      license=LICENSE,
      url=URL,
      long_description=LONG_DESCRIPTION,
      cmdclass=cmdclassd,
      zip_safe=False,
      use_2to3=False,
      python_requires='>={}'.format(__minimum_python_version__),
      **package_info
)
