#
# Kivy - Cross-platform UI framework
# https://kivy.org/
#

import sys
build_examples = False
if "--build_examples" in sys.argv:
    build_examples = True
    sys.argv.remove("--build_examples")

from kivy.utils import pi_version
from copy import deepcopy
import os
from os.path import join, dirname, sep, exists, basename, isdir
from os import walk, environ, makedirs
from distutils.command.build_ext import build_ext
from distutils.version import LooseVersion
from distutils.sysconfig import get_python_inc
from collections import OrderedDict
from time import sleep
from sysconfig import get_paths
from pathlib import Path
import logging
from setuptools import setup, Extension, find_packages


if sys.version_info[0] == 2:
    logging.critical(
        'Unsupported Python version detected!: Kivy 2.0.0 and higher does not '
        'support Python 2. Please upgrade to Python 3, or downgrade Kivy to '
        '1.11.1 - the last Kivy release that still supports Python 2.')


def ver_equal(self, other):
    return self.version == other


# fix error with py3's LooseVersion comparisons
LooseVersion.__eq__ = ver_equal


def get_description():
    with open(join(dirname(__file__), 'README.md'), 'rb') as fileh:
        return fileh.read().decode("utf8").replace('\r\n', '\n')


def getoutput(cmd, env=None):
    import subprocess
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, env=env)
    p.wait()
    if p.returncode:  # if not returncode == 0
        print('WARNING: A problem occurred while running {0} (code {1})\n'
              .format(cmd, p.returncode))
        stderr_content = p.stderr.read()
        if stderr_content:
            print('{0}\n'.format(stderr_content))
        return ""
    return p.stdout.read()


def pkgconfig(*packages, **kw):
    flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}
    lenviron = None
    pconfig = join(sys.prefix, 'libs', 'pkgconfig')

    if isdir(pconfig):
        lenviron = environ.copy()
        lenviron['PKG_CONFIG_PATH'] = '{};{}'.format(
            environ.get('PKG_CONFIG_PATH', ''), pconfig)
    cmd = 'pkg-config --libs --cflags {}'.format(' '.join(packages))
    results = getoutput(cmd, lenviron).split()
    for token in results:
        ext = token[:2].decode('utf-8')
        flag = flag_map.get(ext)
        if not flag:
            continue
        kw.setdefault(flag, []).append(token[2:].decode('utf-8'))
    return kw


def get_isolated_env_paths():
    try:
        # sdl2_dev is installed before setup.py is run, when installing from
        # source due to pyproject.toml. However, it is installed to a
        # pip isolated env, which we need to add to compiler
        import kivy_deps.sdl2_dev as sdl2_dev
    except ImportError:
        return [], []

    root = os.path.abspath(join(sdl2_dev.__path__[0], '../../../..'))
    includes = [join(root, 'Include')] if isdir(join(root, 'Include')) else []
    libs = [join(root, 'libs')] if isdir(join(root, 'libs')) else []
    return includes, libs


# -----------------------------------------------------------------------------
# Determine on which platform we are

build_examples = build_examples or \
    os.environ.get('KIVY_BUILD_EXAMPLES', '0') == '1'

platform = sys.platform

# Detect Python for android project (http://github.com/kivy/python-for-android)
ndkplatform = environ.get('NDKPLATFORM')
if ndkplatform is not None and environ.get('LIBLINK'):
    platform = 'android'
kivy_ios_root = environ.get('KIVYIOSROOT', None)
if kivy_ios_root is not None:
    platform = 'ios'
# proprietary broadcom video core drivers
if exists('/opt/vc/include/bcm_host.h'):
    # The proprietary broadcom video core drivers are not available on the
    # Raspberry Pi 4
    if (pi_version or 4) < 4:
        platform = 'rpi'
# use mesa video core drivers
if environ.get('VIDEOCOREMESA', None) == '1':
    platform = 'vc'
mali_paths = (
    '/usr/lib/arm-linux-gnueabihf/libMali.so',
    '/usr/lib/arm-linux-gnueabihf/mali-egl/libmali.so',
    '/usr/local/mali-egl/libmali.so')
if any((exists(path) for path in mali_paths)):
    platform = 'mali'

# Needed when cross-compiling
if environ.get('KIVY_CROSS_PLATFORM'):
    platform = environ.get('KIVY_CROSS_PLATFORM')

# -----------------------------------------------------------------------------
# Detect options
#
c_options = OrderedDict()
c_options['use_rpi'] = platform == 'rpi'
c_options['use_egl'] = False
c_options['use_opengl_es2'] = None
c_options['use_opengl_mock'] = environ.get('READTHEDOCS', None) == 'True'
c_options['use_sdl2'] = None
c_options['use_pangoft2'] = None
c_options['use_ios'] = False
c_options['use_android'] = False
c_options['use_mesagl'] = False
c_options['use_x11'] = False
c_options['use_wayland'] = False
c_options['use_gstreamer'] = None
c_options['use_avfoundation'] = platform in ['darwin', 'ios']
c_options['use_osx_frameworks'] = platform == 'darwin'
c_options['debug_gl'] = False

# Set the alpha size, this will be 0 on the Raspberry Pi and 8 on all other
# platforms, so SDL2 works without X11
c_options['kivy_sdl_gl_alpha_size'] = 8 if pi_version is None else 0

# now check if environ is changing the default values
for key in list(c_options.keys()):
    ukey = key.upper()
    if ukey in environ:
        # kivy_sdl_gl_alpha_size should be an integer, the rest are booleans
        value = int(environ[ukey])
        if key != 'kivy_sdl_gl_alpha_size':
            value = bool(value)
        print('Environ change {0} -> {1}'.format(key, value))
        c_options[key] = value

use_embed_signature = environ.get('USE_EMBEDSIGNATURE', '0') == '1'
use_embed_signature = use_embed_signature or bool(
    platform not in ('ios', 'android'))

# -----------------------------------------------------------------------------
# We want to be able to install kivy as a wheel without a dependency
# on cython, but we also want to use cython where possible as a setup
# time dependency through `pyproject.toml` if building from source.

# There are issues with using cython at all on some platforms;
# exclude them from using or declaring cython.

# This determines whether Cython specific functionality may be used.
can_use_cython = True

if platform in ('ios', 'android'):
    # NEVER use or declare cython on these platforms
    print('Not using cython on %s' % platform)
    can_use_cython = False


# -----------------------------------------------------------------------------
# Setup classes

# the build path where kivy is being compiled
src_path = build_path = dirname(__file__)
print("Current directory is: {}".format(os.getcwd()))
print("Source and initial build directory is: {}".format(src_path))

# __version__ is imported by exec, but help linter not complain
__version__ = None
with open(join(src_path, 'kivy', '_version.py'), encoding="utf-8") as f:
    exec(f.read())


class KivyBuildExt(build_ext, object):

    def __new__(cls, *a, **kw):
        # Note how this class is declared as a subclass of distutils
        # build_ext as the Cython version may not be available in the
        # environment it is initially started in. However, if Cython
        # can be used, setuptools will bring Cython into the environment
        # thus its version of build_ext will become available.
        # The reason why this is done as a __new__ rather than through a
        # factory function is because there are distutils functions that check
        # the values provided by cmdclass with issublcass, and so it would
        # result in an exception.
        # The following essentially supply a dynamically generated subclass
        # that mix in the cython version of build_ext so that the
        # functionality provided will also be executed.
        if can_use_cython:
            from Cython.Distutils import build_ext as cython_build_ext
            build_ext_cls = type(
                'KivyBuildExt', (KivyBuildExt, cython_build_ext), {})
            return super(KivyBuildExt, cls).__new__(build_ext_cls)
        else:
            return super(KivyBuildExt, cls).__new__(cls)

    def finalize_options(self):
        retval = super(KivyBuildExt, self).finalize_options()

        # Build the extensions in parallel if the options has not been set
        if hasattr(self, 'parallel') and self.parallel is None:
            # Use a maximum of 4 cores. If cpu_count returns None, then parallel
            # build will be disabled
            self.parallel = min(4, os.cpu_count() or 0)
            if self.parallel:
                print('Building extensions in parallel using {} cores'.format(
                    self.parallel))

        global build_path
        if (self.build_lib is not None and exists(self.build_lib) and
                not self.inplace):
            build_path = self.build_lib
            print("Updated build directory to: {}".format(build_path))

        return retval

    def build_extensions(self):
        # build files
        config_h_fn = ('include', 'config.h')
        config_pxi_fn = ('include', 'config.pxi')
        config_py_fn = ('setupconfig.py', )

        # generate headers
        config_h = '// Autogenerated file for Kivy C configuration\n'
        config_h += '#define __PY3 1\n'
        config_pxi = '# Autogenerated file for Kivy Cython configuration\n'
        config_pxi += 'DEF PY3 = 1\n'
        config_py = '# Autogenerated file for Kivy configuration\n'
        config_py += 'PY3 = 1\n'
        config_py += 'CYTHON_MIN = {0}\nCYTHON_MAX = {1}\n'.format(
            repr(MIN_CYTHON_STRING), repr(MAX_CYTHON_STRING))
        config_py += 'CYTHON_BAD = {0}\n'.format(repr(', '.join(map(
            str, CYTHON_UNSUPPORTED))))

        # generate content
        print('Build configuration is:')
        for opt, value in c_options.items():
            # kivy_sdl_gl_alpha_size is already an integer
            if opt != 'kivy_sdl_gl_alpha_size':
                value = int(bool(value))
            print(' * {0} = {1}'.format(opt, value))
            opt = opt.upper()
            config_h += '#define __{0} {1}\n'.format(opt, value)
            config_pxi += 'DEF {0} = {1}\n'.format(opt, value)
            config_py += '{0} = {1}\n'.format(opt, value)
        debug = bool(self.debug)
        print(' * debug = {0}'.format(debug))

        config_pxi += 'DEF DEBUG = {0}\n'.format(debug)
        config_py += 'DEBUG = {0}\n'.format(debug)
        config_pxi += 'DEF PLATFORM = "{0}"\n'.format(platform)
        config_py += 'PLATFORM = "{0}"\n'.format(platform)
        for fn, content in (
                (config_h_fn, config_h), (config_pxi_fn, config_pxi),
                (config_py_fn, config_py)):
            build_fn = expand(build_path, *fn)
            if self.update_if_changed(build_fn, content):
                print('Updated {}'.format(build_fn))
            src_fn = expand(src_path, *fn)
            if src_fn != build_fn and self.update_if_changed(src_fn, content):
                print('Updated {}'.format(src_fn))

        c = self.compiler.compiler_type
        print('Detected compiler is {}'.format(c))
        if c != 'msvc':
            for e in self.extensions:
                e.extra_link_args += ['-lm']

        super(KivyBuildExt, self).build_extensions()

    def update_if_changed(self, fn, content):
        need_update = True
        if exists(fn):
            with open(fn) as fd:
                need_update = fd.read() != content
        if need_update:
            directory_name = dirname(fn)
            if not exists(directory_name):
                makedirs(directory_name)
            with open(fn, 'w') as fd:
                fd.write(content)
        return need_update


def _check_and_fix_sdl2_mixer(f_path):
    # Between SDL_mixer 2.0.1 and 2.0.4, the included frameworks changed
    # smpeg2 have been replaced with mpg123, but there is no need to fix.
    smpeg2_path = ("{}/Versions/A/Frameworks/smpeg2.framework"
                   "/Versions/A/smpeg2").format(f_path)
    if not exists(smpeg2_path):
        return

    print("Check if SDL2_mixer smpeg2 have an @executable_path")
    rpath_from = ("@executable_path/../Frameworks/SDL2.framework"
                  "/Versions/A/SDL2")
    rpath_to = "@rpath/../../../../SDL2.framework/Versions/A/SDL2"
    output = getoutput(("otool -L '{}'").format(smpeg2_path)).decode('utf-8')
    if "@executable_path" not in output:
        return

    print("WARNING: Your SDL2_mixer version is invalid")
    print("WARNING: The smpeg2 framework embedded in SDL2_mixer contains a")
    print("WARNING: reference to @executable_path that will fail the")
    print("WARNING: execution of your application.")
    print("WARNING: We are going to change:")
    print("WARNING: from: {}".format(rpath_from))
    print("WARNING: to: {}".format(rpath_to))
    getoutput("install_name_tool -change {} {} {}".format(
        rpath_from, rpath_to, smpeg2_path))

    output = getoutput(("otool -L '{}'").format(smpeg2_path))
    if b"@executable_path" not in output:
        print("WARNING: Change successfully applied!")
        print("WARNING: You'll never see this message again.")
    else:
        print("WARNING: Unable to apply the changes, sorry.")


# -----------------------------------------------------------------------------
print("Python path is:\n{}\n".format('\n'.join(sys.path)))
# extract version (simulate doc generation, kivy will be not imported)
environ['KIVY_DOC_INCLUDE'] = '1'
import kivy

# Cython check
# on python-for-android and kivy-ios, cython usage is external
from kivy.tools.packaging.cython_cfg import get_cython_versions, get_cython_msg
CYTHON_REQUIRES_STRING, MIN_CYTHON_STRING, MAX_CYTHON_STRING, \
    CYTHON_UNSUPPORTED = get_cython_versions()
cython_min_msg, cython_max_msg, cython_unsupported_msg = get_cython_msg()

if can_use_cython:
    import Cython
    print('\nFound Cython at', Cython.__file__)

    cy_version_str = Cython.__version__
    cy_ver = LooseVersion(cy_version_str)
    print('Detected supported Cython version {}'.format(cy_version_str))

    if cy_ver < LooseVersion(MIN_CYTHON_STRING):
        print(cython_min_msg)
    elif cy_ver in CYTHON_UNSUPPORTED:
        print(cython_unsupported_msg)
    elif cy_ver > LooseVersion(MAX_CYTHON_STRING):
        print(cython_max_msg)
    sleep(1)

# extra build commands go in the cmdclass dict {'command-name': CommandClass}
# see tools.packaging.{platform}.build.py for custom build commands for
# portable packages. Also e.g. we use build_ext command from cython if its
# installed for c extensions.
from kivy.tools.packaging.factory import FactoryBuild
cmdclass = {
    'build_factory': FactoryBuild,
    'build_ext': KivyBuildExt}

try:
    # add build rules for portable packages to cmdclass
    if platform == 'win32':
        from kivy.tools.packaging.win32.build import WindowsPortableBuild
        cmdclass['build_portable'] = WindowsPortableBuild
    elif platform == 'darwin':
        from kivy.tools.packaging.osx.build import OSXPortableBuild
        cmdclass['build_portable'] = OSXPortableBuild
except ImportError:
    print('User distribution detected, avoid portable command.')

# Detect which opengl version headers to use
if platform in ('android', 'darwin', 'ios', 'rpi', 'mali', 'vc'):
    c_options['use_opengl_es2'] = True
elif c_options['use_opengl_es2'] is None:
    c_options['use_opengl_es2'] = \
        environ.get('KIVY_GRAPHICS', '').lower() == 'gles'

print('Using this graphics system: {}'.format(
    ['OpenGL', 'OpenGL ES 2'][int(c_options['use_opengl_es2'] or False)]))

# check if we are in a kivy-ios build
if platform == 'ios':
    print('Kivy-IOS project environment detect, use it.')
    print('Kivy-IOS project located at {0}'.format(kivy_ios_root))
    c_options['use_ios'] = True
    c_options['use_sdl2'] = True

elif platform == 'android':
    c_options['use_android'] = True

# detect gstreamer, only on desktop
# works if we forced the options or in autodetection
if platform not in ('ios', 'android') and (c_options['use_gstreamer']
                                           in (None, True)):
    gstreamer_valid = False
    if c_options['use_osx_frameworks'] and platform == 'darwin':
        # check the existence of frameworks
        f_path = '/Library/Frameworks/GStreamer.framework'
        if not exists(f_path):
            c_options['use_gstreamer'] = False
            print('GStreamer framework not found, fallback on pkg-config')
        else:
            print('GStreamer framework found')
            gstreamer_valid = True
            c_options['use_gstreamer'] = True
            gst_flags = {
                'extra_link_args': [
                    '-F/Library/Frameworks',
                    '-Xlinker', '-rpath',
                    '-Xlinker', '/Library/Frameworks',
                    '-Xlinker', '-headerpad',
                    '-Xlinker', '190',
                    '-framework', 'GStreamer'],
                'include_dirs': [join(f_path, 'Headers')]}
    elif platform == 'win32':
        gst_flags = pkgconfig('gstreamer-1.0')
        if 'libraries' in gst_flags:
            print('GStreamer found via pkg-config')
            gstreamer_valid = True
            c_options['use_gstreamer'] = True
        else:
            _includes = get_isolated_env_paths()[0] + [get_paths()['include']]
            for include_dir in _includes:
                if exists(join(include_dir, 'gst', 'gst.h')):
                    print('GStreamer found via gst.h')
                    gstreamer_valid = True
                    c_options['use_gstreamer'] = True
                    gst_flags = {
                        'libraries':
                            ['gstreamer-1.0', 'glib-2.0', 'gobject-2.0']}
                    break

    if not gstreamer_valid:
        # use pkg-config approach instead
        gst_flags = pkgconfig('gstreamer-1.0')
        if 'libraries' in gst_flags:
            print('GStreamer found via pkg-config')
            c_options['use_gstreamer'] = True


# detect SDL2, only on desktop and iOS, or android if explicitly enabled
# works if we forced the options or in autodetection
sdl2_flags = {}
if platform == 'win32' and c_options['use_sdl2'] is None:
    c_options['use_sdl2'] = True

if c_options['use_sdl2'] or (
        platform not in ('android',) and c_options['use_sdl2'] is None):

    sdl2_valid = False
    if c_options['use_osx_frameworks'] and platform == 'darwin':
        # check the existence of frameworks
        sdl2_frameworks_search_path = environ.get(
            "KIVY_SDL2_FRAMEWORKS_SEARCH_PATH", "/Library/Frameworks"
        )
        sdl2_valid = True
        sdl2_flags = {
            'extra_link_args': [
                '-F{}'.format(sdl2_frameworks_search_path),
                '-Xlinker', '-rpath',
                '-Xlinker', sdl2_frameworks_search_path,
                '-Xlinker', '-headerpad',
                '-Xlinker', '190'],
            'include_dirs': [],
            'extra_compile_args': ['-F{}'.format(sdl2_frameworks_search_path)]
        }
        for name in ('SDL2', 'SDL2_ttf', 'SDL2_image', 'SDL2_mixer'):
            f_path = '{}/{}.framework'.format(sdl2_frameworks_search_path, name)
            if not exists(f_path):
                print('Missing framework {}'.format(f_path))
                sdl2_valid = False
                continue
            sdl2_flags['extra_link_args'] += ['-framework', name]
            sdl2_flags['include_dirs'] += [join(f_path, 'Headers')]
            print('Found sdl2 frameworks: {}'.format(f_path))
            if name == 'SDL2_mixer':
                _check_and_fix_sdl2_mixer(f_path)

        if not sdl2_valid:
            c_options['use_sdl2'] = False
            print('SDL2 frameworks not found, fallback on pkg-config')
        else:
            c_options['use_sdl2'] = True
            print('Activate SDL2 compilation')

    if not sdl2_valid and platform != "ios":