"""This module is for Python-based integration tests that don't belong anywhere
else."""

import os
import re
import subprocess

import pytest

from gitubuntu.repo_builder import (
    Commit,
    Placeholder,
    Repo,
    SourceTree,
)
from gitubuntu.source_builder import (
    Source,
    SourceSpec,
)
from gitubuntu.test_fixtures import pygit2_repo


# Integration with bin/self-test. This allows integration tests to call our
# other direct entry points to test that they work correctly. This relies on
# the environment variables used by bin/self-test. It would be more explicit to
# use command line arguments to pytest itself (eg.
# https://stackoverflow.com/a/61702020/478206) but that approach has its own
# complications because code in conftest.py would be less obvious, so this
# seemed to be the most straightforward method.
#
# Examples of our extra entry points:
#   git-dsc-commit
#   git-reconstruct-changelog
#   git-merge-changelogs
#
# Right now our test coverage of these is limited, but this
# ENTRY_POINT_TYPE/ENTRY_POINT_DIR/get_entry_point() mechanism is generic to
# all our entry points.
#
# There are five ways in which our integration tests may be invoked:
#
# 1) From an installed deb, invoked as /usr/bin/git-ubuntu.self-test.
# 2) From the source tree, with required dependencies provided by the snap.
# 3) From an installed snap, invoked as /snap/bin/git-ubuntu.self-test.
# 4) From the source tree, with required dependencies provided by the system.
# 5) During a deb build, when invoked by dh_auto_test. In this case, the entry
#    points aren't immediately available, so we skip entry point testing. An
#    autopkgtest is in a better position to test this later using invocation 1
#    above.
if 'TEST_SYSTEM_TREE' in os.environ:
    # 1) From an installed deb, invoked as /usr/bin/git-ubuntu.self-test.
    assert 'SNAP' not in os.environ
    ENTRY_POINT_TYPE = 'deb'
    ENTRY_POINT_DIR = '/usr/bin'
elif 'SNAP' in os.environ:
    if 'TEST_TREE' in os.environ:
        # 2) From the source tree, with required dependencies provided by the
        # snap.
        ENTRY_POINT_TYPE = 'source'
        ENTRY_POINT_DIR = os.path.join(os.environ['TEST_TREE'], 'bin')
    else:
        # 3) From an installed snap, invoked as /snap/bin/git-ubuntu.self-test.
        ENTRY_POINT_TYPE = 'snap'
        ENTRY_POINT_DIR = '/snap/bin'
else:
    bindir = os.path.join(os.getcwd(), 'bin')
    if os.path.exists(bindir):
        # 4) From the source tree, with required dependencies provided by the
        # system.
        ENTRY_POINT_TYPE = 'source'
        ENTRY_POINT_DIR = bindir
    else:
        # 5) During a deb build, when invoked by dh_auto_test.
        ENTRY_POINT_TYPE = None

if ENTRY_POINT_TYPE is not None:
    assert os.path.exists(ENTRY_POINT_DIR)


# How we call our entry points currently differ if they're being called
# directly from the source tree, since the wrappers have more standardised
# names. This mapping allows us to use the right name regardless of how we're
# calling it. Right now, as our test coverage is limited, only
# the mapping for reconstruct-changelog is included; however this structure
# allows us to later expand test coverage to the other entry points also.
ENTRY_POINT_MAP = {
    'snap': {'reconstruct-changelog': 'git-ubuntu.reconstruct-changelog'},
    'deb': {'reconstruct-changelog': 'git-ubuntu.reconstruct-changelog'},
    'source': {'reconstruct-changelog': 'git-reconstruct-changelog'},
}


def get_entry_point(name):
    '''Return the name with which to invoke a specific entry point.

    How we call our entry points currently differ if they're being called
    directly from the source tree, since the wrappers have more standardised
    names.

    Calling this function only makes sense if entry points are available (ie.
    ENTRY_POINT_TYPE is not None). Calling without entry points available is
    not permitted and so this is asserted internally.

    :param str name: our general name for the entry point, as keyed by
        ENTRY_POINT_MAP.
    :rtype: str
    :returns: the name with which we can expect to invoke the entry point
    '''
    assert ENTRY_POINT_TYPE is not None
    return os.path.join(
        ENTRY_POINT_DIR,
        ENTRY_POINT_MAP[ENTRY_POINT_TYPE][name],
    )


@pytest.mark.parametrize(['command', 'params'], [
    # Test that awk works. awk is used indirectly via quilt but has failed in
    # the snap previously because of an interaction between the core snap, the
    # awk binary and readline.
    ('awk', ['']),
    # Test that sed works. sed is used indirectly via
    # git-ubuntu.reconstruct-changelog, so this mirrors the test_awk_runnable()
    # test above. However "sed" on its own waits for input indefinitely, so we
    # use --version.
    ('sed', ['--version']),
    # Test that perl dependent binaries work. In the past, these used to leak
    # dependency requests to use perl libraries from the host machine, which
    # could be incompatible with the versions in the git-ubuntu snap.
    ('dpkg-parsechangelog', ['--version']),
    ('dpkg-source', ['--version']),
    ('dpkg-mergechangelogs', ['--version']),
    ('pristine-tar', ['--help']),
    ('pristine-xz', ['--help']),
    ('pristine-gz', ['--help']),
    ('pristine-bz2', ['--help']),
    ('dch', ['--version'])
])
def test_command_runnable(command, params):
    subprocess.check_call([command, *params])


@pytest.mark.parametrize(['compressor', 'decompressor'], [
    # The following list of decompressors is taken from the keys of $COMP in
    # scripts/Dpkg/Compression.pm from the dpkg source. It may need to be
    # updated if future dpkg updates add additional compression mechanisms.
    ('gzip', 'gunzip',),
    ('bzip2', 'bunzip2',),
    ('xz --format=lzma', 'unxz --format=lzma',),
    ('xz', 'unxz',),
])
def test_dpkg_compressors(compressor, decompressor):
    '''The given dpkg decompressor should be available'''
    # We pass data to compressor and related decompressor and verify
    # if it still matches. This will catch unavailable binaries as well
    # as changed behavior.
    expected = b"Test input data\n"
    test = subprocess.Popen(
        f"{compressor} - | {decompressor}",
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True,
    )
    result = test.communicate(expected)
    assert not test.returncode  # command should have exited without error
    # Output is stdout/stderr tuple. We expect the data we have sent
    # and nothing in stderr
    assert result == (expected, b'')


def test_update_maintainer(tmpdir):
    '''update-maintainer should adjust debian/control as expected'''
    debian_dir = tmpdir.join('debian')
    control_file = debian_dir.join('control')
    control_file.write_text(
        '''Source: test
Maintainer: Test Maintainer <test@example.com>
''',
        ensure=True,
        encoding='utf-8',
    )
    debian_dir.join('changelog').write_text(
        '''test (1) UNRELEASED; urgency=medium
  * Test change.

 -- Test Maintainer <test@example.com>  Tue, 01 Jun 2021 14:09:49 +0000
''',
        ensure=True,
        encoding='utf-8',
    )
    subprocess.check_call(['update-maintainer'], cwd=tmpdir)
    lines = control_file.readlines()
    assert (
        "XSBC-Original-Maintainer: Test Maintainer <test@example.com>\n"
        in lines
    )


@pytest.mark.skipif(
    ENTRY_POINT_TYPE is None,
    reason="Entry point testing not available",
)
def test_reconstruct_changelog(pygit2_repo, monkeypatch):
    '''The reconstruct-changelog endpoint should add the expected commit'''
    monkeypatch.setenv('DEBFULLNAME', 'Test User')
    monkeypatch.setenv('DEBEMAIL', 'test@example.com')
    Repo(
        commits=[
            Commit(tree=SourceTree(Source()), name='root'),
            Commit(
                tree=SourceTree(Source(spec=SourceSpec(mutate=1))),
                message='  * Test changelog entry',
                name='child',
                parents=[Placeholder('root')],
            ),
        ],
        tags={'root': Placeholder('root'), 'child': Placeholder('child')},
    ).write(pygit2_repo)
    pygit2_repo.checkout('refs/tags/child')
    subprocess.check_call(
        [get_entry_point('reconstruct-changelog'), 'HEAD^'],
        cwd=pygit2_repo.workdir,
    )
    with open(os.path.join(pygit2_repo.workdir, 'debian/changelog'), 'r') as f:
        changelog_lines = f.read().splitlines()
    assert changelog_lines[0:4] == [
        'source-builder-package (1-1ubuntu1) UNRELEASED; urgency=medium',
        '',
        '  * Test changelog entry',
        '',
    ]
    assert changelog_lines[4].startswith(' -- Test User <test@example.com>')
    assert changelog_lines[5] == ''


@pytest.mark.skipif(
    ENTRY_POINT_TYPE != 'snap',
    reason="snap related test",
)
@pytest.mark.parametrize(
    'dpkg_tool', ['parsechangelog', 'source', 'mergechangelogs']
)
def test_dpkg_tooling_confined(dpkg_tool):
    '''Test that the dpkg tooling is not using the host's perl modules

    When using the host's perl modules, --version will load variables from
    the host's dpkg perl module and will report the host's dpkg version.
    '''
    tool_version_str = subprocess.check_output(
        ['dpkg-%s' % dpkg_tool, '--version']
    ).decode()
    dpkg_version_str = subprocess.check_output(['dpkg', '--version']).decode()
    tool_version = re.search(r'version (\d+\.\d+\.\d+)', tool_version_str)
    dpkg_version = re.search(r'version (\d+\.\d+\.\d+)', dpkg_version_str)
    assert tool_version.group(1) == dpkg_version.group(1)
