# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

include('build/moz.configure/init.configure')

# Note:
# - Gecko-specific options and rules should go in toolkit/moz.configure.
# - Firefox-specific options and rules should go in browser/moz.configure.
# - Fennec-specific options and rules should go in
#   mobile/android/moz.configure.
# - Spidermonkey-specific options and rules should go in js/moz.configure.
# - etc.

option('--enable-artifact-builds', env='MOZ_ARTIFACT_BUILDS',
       help='Download and use prebuilt binary artifacts.')

@depends('--enable-artifact-builds')
def artifact_builds(value):
    if value:
        return True

set_config('MOZ_ARTIFACT_BUILDS', artifact_builds)

imply_option('--enable-artifact-build-symbols',
             depends(artifact_builds)(lambda v: False if v is None else None),
             reason='--disable-artifact-builds')

option('--enable-artifact-build-symbols',
       help='Download symbols when artifact builds are enabled.')

set_config('MOZ_ARTIFACT_BUILD_SYMBOLS',
           depends_if('--enable-artifact-build-symbols')(lambda _: True))

@depends('--enable-artifact-builds')
def imply_disable_compile_environment(value):
    if value:
        return False

imply_option('--enable-compile-environment', imply_disable_compile_environment)

option('--disable-compile-environment',
       help='Disable compiler/library checks')

@depends('--disable-compile-environment')
def compile_environment(compile_env):
    if compile_env:
        return True

set_config('COMPILE_ENVIRONMENT', compile_environment)
add_old_configure_assignment('COMPILE_ENVIRONMENT', compile_environment)

js_option('--enable-debug',
          nargs='?',
          help='Enable building with developer debug info '
               '(using the given compiler flags).')

add_old_configure_assignment('MOZ_DEBUG',
                             depends('--enable-debug')(lambda v: bool(v)))

include('build/moz.configure/pkg.configure')
# Make this assignment here rather than in pkg.configure to avoid
# requiring this file in unit tests.
add_old_configure_assignment('PKG_CONFIG', pkg_config)

include('build/moz.configure/toolchain.configure',
        when='--enable-compile-environment')
include('build/moz.configure/memory.configure',
        when='--enable-compile-environment')
include('build/moz.configure/headers.configure',
        when='--enable-compile-environment')
include('build/moz.configure/warnings.configure',
        when='--enable-compile-environment')

include(include_project_configure)

@depends('--help')
@imports(_from='mozbuild.backend', _import='backends')
def build_backends_choices(_):
    return tuple(backends)


@deprecated_option('--enable-build-backend', nargs='+',
                   choices=build_backends_choices)
def build_backend(backends):
    if backends:
        return tuple('+%s' % b for b in backends)

imply_option('--build-backends', build_backend)


@depends('--enable-artifact-builds', '--disable-compile-environment', '--help')
@imports('sys')
def build_backend_defaults(artifact_builds, compile_environment, _):
    if artifact_builds:
        all_backends = ['FasterMake+RecursiveMake']
    else:
        all_backends = ['RecursiveMake', 'FasterMake']
    # Normally, we'd use target.os == 'WINNT', but a dependency on target
    # would require target to depend on --help, as well as host and shell,
    # and this is not a can of worms we can open at the moment.
    if sys.platform == 'win32' and compile_environment:
        all_backends.append('VisualStudio')
    return tuple(all_backends)

option('--build-backends', nargs='+', default=build_backend_defaults,
       choices=build_backends_choices, help='Build backends to generate')

@depends('--build-backends')
def build_backends(backends):
    return backends

set_config('BUILD_BACKENDS', build_backends)


# Awk detection
# ==============================================================
awk = check_prog('AWK', ('gawk', 'mawk', 'nawk', 'awk'))

# Until the AWK variable is not necessary in old-configure
@depends(awk)
def awk_for_old_configure(value):
    return value

add_old_configure_assignment('AWK', awk_for_old_configure)


# Perl detection
# ==============================================================
perl = check_prog('PERL', ('perl5', 'perl'))

# Until the PERL variable is not necessary in old-configure
@depends(perl)
def perl_for_old_configure(value):
    return value

add_old_configure_assignment('PERL', perl_for_old_configure)

@template
def perl_version_check(min_version):
    @depends(perl)
    @checking('for minimum required perl version >= %s' % min_version)
    def get_perl_version(perl):
        return Version(check_cmd_output(
            perl, '-e', 'print $]',
            onerror=lambda: die('Failed to get perl version.')
        ))

    @depends(get_perl_version)
    def check_perl_version(version):
        if version < min_version:
            die('Perl %s or higher is required.', min_version)

    @depends(perl)
    @checking('for full perl installation')
    @imports('subprocess')
    def has_full_perl_installation(perl):
        ret = subprocess.call(
            [perl, '-e', 'use Config; exit(!-d $Config{archlib})'])
        return ret == 0

    @depends(has_full_perl_installation)
    def require_full_perl_installation(has_full_perl_installation):
        if not has_full_perl_installation:
            die('Cannot find Config.pm or $Config{archlib}. '
                'A full perl installation is required.')

perl_version_check('5.006')


# GNU make detection
# ==============================================================
option(env='MAKE', nargs=1, help='Path to GNU make')

@depends('MAKE', host)
def possible_makes(make, host):
    candidates = []
    if host.kernel == 'WINNT':
        candidates.append('mingw32-make')
    if make:
        candidates.append(make[0])
    if host.kernel == 'WINNT':
        candidates.extend(('make', 'gmake'))
    else:
        candidates.extend(('gmake', 'make'))
    return candidates

check_prog('GMAKE', possible_makes)

# tup detection
# ==============================================================
@depends(build_backends)
def tup_progs(build_backends):
    for backend in build_backends:
        if 'Tup' in backend:
            return ['tup']
    return None

tup = check_prog('TUP', tup_progs)

# Miscellaneous programs
# ==============================================================
check_prog('DOXYGEN', ('doxygen',), allow_missing=True)
check_prog('XARGS', ('xargs',))

@depends(target)
def extra_programs(target):
    if target.kernel == 'Darwin':
        return namespace(
            DSYMUTIL=('dsymutil', 'llvm-dsymutil'),
            GENISOIMAGE=('genisoimage',),
        )
    if target.os == 'GNU' and target.kernel == 'Linux':
        return namespace(RPMBUILD=('rpmbuild',))

check_prog('DSYMUTIL', delayed_getattr(extra_programs, 'DSYMUTIL'),
           allow_missing=True)
check_prog('GENISOIMAGE', delayed_getattr(extra_programs, 'GENISOIMAGE'),
           allow_missing=True)
check_prog('RPMBUILD', delayed_getattr(extra_programs, 'RPMBUILD'),
           allow_missing=True)

option('--enable-system-hunspell',
       help="Use system hunspell (located with pkgconfig)")

@depends('--enable-system-hunspell', compile_environment)
def check_for_hunspell(value, compile_env):
    return value and compile_env

system_hunspell = pkg_check_modules('MOZ_HUNSPELL', 'hunspell',
                                    when=check_for_hunspell)

set_config('MOZ_SYSTEM_HUNSPELL', depends_if(system_hunspell)(lambda _: True))


@depends(target)
@imports('os')
def makensis_progs(target):
    if target.kernel != 'WINNT':
        return

    candidates = [
        'makensis-3.01.exe',
        'makensis-3.0b3.exe',
        'makensis-3.0b1.exe',
        'makensis.exe',
        'makensis',
    ]

    # Look for nsis installed by msys environment. But only the 32-bit version.
    # We use an absolute path and insert as the first entry so it is preferred
    # over a 64-bit exe that may be in PATH.
    if 'MSYSTEM_PREFIX' in os.environ:
        prefix = os.path.dirname(os.environ['MSYSTEM_PREFIX'])
        candidates.insert(0, os.path.join(prefix, 'mingw32', 'bin', 'makensis.exe'))

    return tuple(candidates)

nsis = check_prog('MAKENSISU', makensis_progs)

# Make sure the version of makensis is up to date.
@depends_if(nsis)
@checking('for NSIS version')
@imports('re')
def nsis_version(nsis):
    nsis_min_version = '3.0b1'
    out = check_cmd_output(nsis, '-version',
                           onerror=lambda: die('Failed to get nsis version.'))
    m = re.search(r'(?<=v)[0-9]+\.[0-9]+((a|b|rc)[0-9]+)?', out)

    if not m:
        raise FatalCheckError('Unknown version of makensis')
    ver = Version(m.group(0))

    # Versions comparisons don't quite work well with beta versions, so ensure
    # it works for the non-beta version.
    if ver < nsis_min_version and (ver >= '3.0a' or ver < '3'):
        raise FatalCheckError('To build the installer you must have NSIS'
                              ' version %s or greater in your path'
                              % nsis_min_version)

    return ver

# And that makensis is 32-bit.
@depends_if(nsis)
@checking('for 32-bit NSIS')
def nsis_binary_type(nsis):
    bin_type = windows_binary_type(nsis)
    if bin_type != 'win32':
        raise FatalCheckError('%s is not a 32-bit Windows application' % nsis)

    return 'yes'


# Fallthrough to autoconf-based configure
include('build/moz.configure/old.configure')
# Please do not add anything after the include of old.configure.