#!/usr/bin/env python
# (c)quasardb SAS. All rights reserved.
# qdb is a trademark of quasardb SAS

# pylint: disable=C0103,C0111,C0326,W0201

from builtins import range as xrange  # pylint: disable=W0622
import glob
import os
import sys
from setuptools import setup, Extension
import ez_setup
ez_setup.use_setuptools()

qdb_version = "2.5.0".lower()

is_clang = 'Clang' in 'MSVC'
is_windows = os.name == 'nt'
is_freebsd = sys.platform.startswith('freebsd')
is_linux = sys.platform.startswith('linux')
is_osx = sys.platform == 'darwin'
is_64_bits = sys.maxsize > 2**32
arch = "x64" if is_64_bits else "x86"

if is_windows:
    extra_compile_args = [
        '/DSTATIC_LINKED',  # a hack to avoid double export definition
        # because we already set "dllexport" in the source code
        # generated by SWIG except when STATIC_LINKED is set
        '/EHsc',
        '/MT']  # overrides the /MD that is send by distutils,
    # this will generate command line warning D9025 (cannot be disabled)
    extra_link_args = [
        '/INCREMENTAL:NO', '/OPT:REF', '/RELEASE',
        '/DYNAMICBASE', '/NXCOMPAT', '/FUNCTIONPADMIN', '/MANIFEST']
    if is_64_bits:
        extra_link_args += ['/machine:x64']
    else:
        extra_link_args += ['/machine:x86', '/LARGEADDRESSAWARE']
else:
    if is_clang:
        extra_compile_args = [
            '-std=c++11', '-stdlib=libc++', '-fcxx-exceptions', '-fexceptions']
        extra_link_args = []
    else:
        extra_compile_args = ['-std=c++11', '-Wno-unused-function']
        extra_link_args = ['-static-libgcc', '-static-libstdc++']

    if is_linux:
        extra_link_args += ['-Wl,--wrap=memcpy']

    if not is_osx:
        extra_link_args += ['-Wl,-z,origin',
                            '-Wl,--gc-sections', '-Wl,-R$ORIGIN']


if is_freebsd:
    # on FreeBSD everything should be in the system
    qdb_libraries = ['qdb_api', 'c++']
else:
    qdb_libraries = ['qdb_api']

package_modules = glob.glob(os.path.join('C:/TeamCity/work/7d78e68d339804b4', 'qdb', 'qdb_api.*'))
if is_osx:
    package_modules.extend(glob.glob(os.path.join('C:/TeamCity/work/7d78e68d339804b4', 'qdb', 'lib', '*.lib *.dll')))

package_name = 'quasardb'

try:
    from setuptools.command.bdist_egg import bdist_egg as old_bdist_egg  # pylint: disable=C0412
    from pkg_resources import get_build_platform

    class EggRetagger(old_bdist_egg):
        def finalize_options(self):
            if self.plat_name is None:
                self.plat_name = get_build_platform()

            if self.plat_name.startswith('freebsd'):
                parts = self.plat_name.split('-')
                self.plat_name = parts[0] + '-' + \
                    parts[1].split('.')[0] + '-' + parts[-1]

            old_bdist_egg.finalize_options(self)

    from wheel.bdist_wheel import bdist_wheel as old_bdist_wheel

    class WheelRetagger(old_bdist_wheel):
        def get_tag(self):
            tag = old_bdist_wheel.get_tag(self)

            python_tag = tag[0]
            abi_tag = tag[1]
            platform_tag = tag[2]

            if platform_tag.startswith('freebsd'):
                parts = platform_tag.split('_')
                platform_tag = '_'.join(parts[:2]) + '_' + parts[-1]

            if platform_tag.startswith('macosx_10_') and platform_tag.endswith('_x86_64'):
                supported_versions = [
                    'macosx_10_6', 'macosx_10_9', 'macosx_10_10', 'macosx_10_11', 'macosx_10_12']
                for i in xrange(len(supported_versions)):
                    supported_versions[i] = supported_versions[i] + '_x86_64'
                platform_tag = '.'.join(supported_versions)

            tag = (python_tag, abi_tag, platform_tag)
            return tag

    cmdclass = {
        'bdist_egg': EggRetagger,
        'bdist_wheel': WheelRetagger,
    }
except ImportError:
    cmdclass = {}

setup(name=package_name,
      version=qdb_version,
      description='Python API for quasardb',
      author='quasardb SAS',
      author_email='contact@quasardb.net',
      url='https://www.quasardb.net/',
      classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Intended Audience :: End Users/Desktop',
          'Intended Audience :: Financial and Insurance Industry',
          'Intended Audience :: Information Technology',
          'Intended Audience :: Other Audience',
          'Intended Audience :: System Administrators',
          'Intended Audience :: Telecommunications Industry',
          'Programming Language :: Python :: 2.7',
          'Topic :: Database',
          'Topic :: Software Development :: Libraries :: Python Modules',
      ],
      keywords='quasardb timeseries database API driver ',
      setup_requires=["setuptools_git >= 0.3", "xmlrunner", "future"],
      install_requires=["xmlrunner", "future", "pytz", "tzlocal"],
      packages=[package_name],
      package_data={package_name: [
          os.path.basename(mod) for mod in package_modules]},
      include_package_data=True,
      ext_modules=[Extension(
          'quasardb._qdb', [
              os.path.join('src', 'qdb_python_wrapper.cxx'),
              os.path.join('src', 'memcpy_wrap.cxx')],
          include_dirs=['include'],
          library_dirs=[package_name],
          libraries=qdb_libraries,
          extra_compile_args=extra_compile_args,
          extra_link_args=extra_link_args)],
      cmdclass=cmdclass,
      zip_safe=True,
     )
