#!/usr/bin/env python3

# Copyright 2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.
"""
Debusine integration tests.

Test Sbuild task.
"""

import glob
import logging
import subprocess
import time
import unittest
from pathlib import Path
from typing import Any, Optional

from utils import common
from utils.client import Client
from utils.common import Configuration, launch_tests
from utils.integration_test_helpers_mixin import IntegrationTestHelpersMixin
from utils.server import DebusineServer
from utils.worker import Worker

import yaml

logger = logging.getLogger(__name__)


class IntegrationTaskSbuildTests(
    IntegrationTestHelpersMixin, unittest.TestCase
):
    """
    Integration test for the sbuild task.

    These tests assume:
    - debusine-server is running
    - debusine-worker is running (connected to the server)
    - debusine-client is correctly configured
    - "sudo -u debusine-server debusine-admin commands" works
    - schroot "chroot:stable-{architecture}-sbuild" is set up
    - there is one artifact of category "debian:system-tarball" for "bookworm"
    - environment variable AUTOPKGTEST_TMP is set

    debusine-worker is not started (neither restarted) during the tests.
    """

    TASK_NAME = 'sbuild'

    def setUp(self) -> None:
        """Initialize test."""
        self._sbuild_changes_file_path: Optional[Path] = None

        # If debusine-server or nginx was launched just before the
        # integration-tests.py is launched the debusine-server might not be
        # yet available. Let's wait for the debusine-server to be
        # reachable if it's not ready yet
        self.assertTrue(
            DebusineServer.wait_for_server_ready(),
            'debusine-server should be available (in '
            f'{Configuration.BASE_URL}) before the integration tests are ran',
        )

        self.distribution = "stable"
        self.architecture = subprocess.check_output(
            ["dpkg", "--print-architecture"], text=True
        ).strip()

        self.assertTrue(
            self.schroot_available(self.distribution, self.architecture)
        )

        self._environment_id = self.find_system_image(suite="bookworm")

        self._worker = Worker()

    def test_work_request_sbuild_schroot(self):
        """Create an sbuild job: use "schroot" backend."""
        artifact_id = self.create_artifact_source("hello")

        task_data = self.create_task_data_from_artifact(
            architecture=self.architecture,
            source_artifact_id=artifact_id,
            backend="schroot",
            distribution=self.distribution,
        )

        self.submit_verify_work_request(task_data)

    def test_work_request_sbuild_unshare(self):
        """Create an sbuild job: use "unshare" backend."""
        artifact_id = self.create_artifact_source("hello")

        task_data = self.create_task_data_from_artifact(
            architecture=self.architecture,
            source_artifact_id=artifact_id,
            backend="unshare",
            environment_id=self._environment_id,
        )

        self.submit_verify_work_request(task_data)

    def submit_verify_work_request(self, task_data: str):
        """Client submit a sbuild work request and assert results."""
        # Client submits a work-request
        work_request_id = Client.execute_command(
            "create-work-request", self.TASK_NAME, stdin=task_data
        )["work_request_id"]

        # The worker should get the new work request and start executing it
        self.assertTrue(
            Client.wait_for_work_request_completed(work_request_id, "success")
        )

        work_request = Client.execute_command(
            "show-work-request", work_request_id
        )

        debian_binary_packages_artifacts = 0
        debian_upload_artifacts = 0
        for artifact in work_request["artifacts"]:
            if artifact["category"] == "debian:binary-packages":
                debian_binary_packages_artifacts += 1

                self.assertEqual(artifact["data"]["srcpkg_name"], "hello")
                self.assertEqual(
                    artifact["data"]["architecture"], self.architecture
                )

                version = artifact["data"]["version"]
                self.assertCountEqual(
                    artifact["files"].keys(),
                    [
                        f"hello_{version}_{self.architecture}.deb",
                        f"hello-dbgsym_{version}_{self.architecture}.deb",
                    ],
                )
            elif artifact["category"] == "debian:upload":
                debian_upload_artifacts += 1

                self.assertEqual(artifact["data"]["type"], "dpkg")
                self.assertEqual(
                    artifact["data"]["changes_fields"]["Source"], "hello"
                )

                version = artifact["data"]["changes_fields"]["Version"]
                self.assertCountEqual(
                    artifact["files"].keys(),
                    [
                        f"hello_{version}_{self.architecture}.deb",
                        f"hello-dbgsym_{version}_{self.architecture}.deb",
                        f"hello_{version}_{self.architecture}.buildinfo",
                        f"hello_{version}_{self.architecture}.changes",
                    ],
                )

        self.assertEqual(debian_binary_packages_artifacts, 1)
        self.assertEqual(debian_upload_artifacts, 1)

    def test_create_sbuild_schroot_not_found(self):
        """Create a sbuild job, schroot does not exist. Status is pending."""
        distribution = 'does-not-exist'
        self.assertFalse(
            self.schroot_available(distribution, self.architecture)
        )

        artifact_id = self.create_artifact_source("hello")

        task_data = self.create_task_data_from_artifact(
            architecture=self.architecture,
            source_artifact_id=artifact_id,
            backend="schroot",
            distribution=distribution,
        )

        # Client submits a work-request
        work_request_id = Client.execute_command(
            'create-work-request', self.TASK_NAME, stdin=task_data
        )['work_request_id']

        # Currently a work request for which there is no an available worker
        # stays in the pending status. Let's wait 5 seconds and check that
        # it is still in pending
        time.sleep(5)

        status = Client.execute_command('show-work-request', work_request_id)

        self.assertEqual(status['status'], 'pending')

        # The file was not created
        self.assertFalse(self.sbuild_changes_file_name().exists())

    @staticmethod
    def schroot_available(distribution: str, architecture: str) -> bool:
        """
        Assert that a specific chroot is available.

        Looks for chroot:{distribution}-{architecture}-sbuild in the output
        of schroot --list

        The integration test does not set up any sbuild but use
        an available one.
        """
        # To set them up see debian/tests/integration-tests-sbuild
        # For example:
        # adduser debusine-worker sbuild
        # sbuild-createchroot stable /srv/chroot/stable)
        output = common.run(['schroot', '--list']).stdout

        expected_line = f'chroot:{distribution}-{architecture}-sbuild'

        return expected_line in output

    def sbuild_changes_file_name(self) -> Path:
        """
        Return path to a non-existing temporary file in /tmp.

        Return the same path for each test. Add cleanup to delete the file.
        """
        if self._sbuild_changes_file_path:
            return self._sbuild_changes_file_path

        self._sbuild_changes_file_path = self.create_temporary_file(
            prefix="sbuild.changes-", directory="/tmp"
        )
        self._sbuild_changes_file_path.unlink()
        return self._sbuild_changes_file_path

    @staticmethod
    def search_file_in_tmp(file_name):
        """Return the absolute file path for file_name in /tmp or None."""
        for file in glob.glob('/tmp/**', recursive=True):
            if file.endswith(file_name):
                return file

        return None

    @staticmethod
    def create_task_data_from_artifact(
        *,
        architecture: str,
        source_artifact_id: int,
        backend: str,
        environment_id: Optional[int] = None,
        distribution: Optional[str] = None,
    ) -> str:
        """Return valid task_data for an sbuild work request from artifact."""
        data: dict[str, Any] = {
            "build_components": ["any", "all"],
            "host_architecture": architecture,
            "input": {"source_artifact_id": source_artifact_id},
            "backend": backend,
        }

        if distribution is not None:
            data["distribution"] = distribution

        if environment_id is not None:
            data["environment_id"] = environment_id

        return yaml.safe_dump(data)


if __name__ == '__main__':
    launch_tests("Task sbuild integration tests for debusine")
