# Copyright (C) 2016-2024 RhodeCode GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# This program is dual-licensed. If you wish to learn more about the
# RhodeCode Enterprise Edition, including its added features, Support services,
# and proprietary license terms, please see https://rhodecode.com/licenses/

import os

import mock
import pytest

from rhodecode.apps.ssh_support.lib.backends.svn import SubversionServer, SubversionTunnelWrapper
from rhodecode.apps.ssh_support.tests.conftest import plain_dummy_env, plain_dummy_user


class SubversionServerCreator(object):
    root = "/tmp/repo/path/"
    svn_path = "/usr/local/bin/svnserve"

    config_data = {
        "app:main": {
            "ssh.executable.svn": svn_path,
            "vcs.hooks.protocol.v2": "celery",
            "app.service_api.host": "http://localhost",
            "app.service_api.token": "secret4",
            "rhodecode.api.url": "/_admin/api",
        }
    }
    repo_name = "test-svn"
    user = plain_dummy_user()

    def __init__(self, service_api_url, ini_file):
        self.service_api_url = service_api_url
        self.ini_file = ini_file
        if not os.path.isdir(self.root):
            os.makedirs(self.root)

    def create(self, **kwargs):
        self.config_data["app:main"]["app.service_api.host"] = self.service_api_url
        parameters = {
            "store": self.root,
            "ini_path": self.ini_file,
            "user": self.user,
            "repo_name": self.repo_name,
            "user_permissions": {self.repo_name: "repository.admin"},
            "settings": self.config_data["app:main"],
            "env": plain_dummy_env(),
        }
        parameters.update(kwargs)
        server = SubversionServer(**parameters)
        return server


@pytest.fixture(scope="module")
def svn_server(request, module_app, rhodecode_factory, available_port_factory):
    ini_file = module_app._pyramid_settings["__file__"]
    vcsserver_host = module_app._pyramid_settings["vcs.server"]

    store_dir = os.path.dirname(ini_file)

    # start rhodecode for service API
    rc = rhodecode_factory(
        request,
        store_dir=store_dir,
        port=available_port_factory(),
        overrides=(
            {"handler_console": {"level": "DEBUG"}},
            {"app:main": {"vcs.server": vcsserver_host}},
            {"app:main": {"repo_store.path": store_dir}},
        ),
    )

    service_api_url = f"http://{rc.bind_addr}"

    return SubversionServerCreator(service_api_url, ini_file)


class TestSubversionServer(object):
    def test_command(self, svn_server):
        server = svn_server.create()
        expected_command = [
            svn_server.svn_path,
            "-t",
            "--config-file",
            server.tunnel.svn_conf_path,
            "--tunnel-user",
            svn_server.user.username,
            "-r",
            svn_server.root,
        ]

        assert expected_command == server.tunnel.command()

    @pytest.mark.parametrize(
        "permissions, action, code",
        [
            ({}, "pull", -2),
            ({"test-svn": "repository.read"}, "pull", 0),
            ({"test-svn": "repository.read"}, "push", -2),
            ({"test-svn": "repository.write"}, "push", 0),
            ({"test-svn": "repository.admin"}, "push", 0),
        ],
    )
    def test_permission_checks(self, svn_server, permissions, action, code):
        server = svn_server.create(user_permissions=permissions)
        result = server._check_permissions(action)
        assert result is code

    @pytest.mark.parametrize(
        "permissions, access_paths, expected_match",
        [
            # not matched repository name
            ({"test-svn": ""}, ["test-svn-1", "test-svn-1/subpath"], None),
            # exact match
            ({"test-svn": ""}, ["test-svn"], "test-svn"),
            # subdir commits
            (
                {"test-svn": ""},
                [
                    "test-svn/foo",
                    "test-svn/foo/test-svn",
                    "test-svn/trunk/development.txt",
                ],
                "test-svn",
            ),
            # subgroups + similar patterns
            (
                {
                    "test-svn": "",
                    "test-svn-1": "",
                    "test-svn-subgroup/test-svn": "",
                },
                [
                    "test-svn-1",
                    "test-svn-1/foo/test-svn",
                    "test-svn-1/test-svn",
                ],
                "test-svn-1",
            ),
            # subgroups + similar patterns
            (
                {
                    "test-svn-1": "",
                    "test-svn-10": "",
                    "test-svn-100": "",
                },
                [
                    "test-svn-10",
                    "test-svn-10/foo/test-svn",
                    "test-svn-10/test-svn",
                ],
                "test-svn-10",
            ),
            # subgroups + similar patterns
            (
                {
                    "name": "",
                    "nameContains": "",
                    "nameContainsThis": "",
                },
                [
                    "nameContains",
                    "nameContains/This",
                    "nameContains/This/test-svn",
                ],
                "nameContains",
            ),
            # subgroups + similar patterns
            (
                {
                    "test-svn": "",
                    "test-svn-1": "",
                    "test-svn-subgroup/test-svn": "",
                },
                [
                    "test-svn-subgroup/test-svn",
                    "test-svn-subgroup/test-svn/foo/test-svn",
                    "test-svn-subgroup/test-svn/trunk/example.txt",
                ],
                "test-svn-subgroup/test-svn",
            ),
        ],
    )
    def test_repo_extraction_on_subdir(self, svn_server, permissions, access_paths, expected_match):
        server = svn_server.create(user_permissions=permissions)
        for path in access_paths:
            repo_name = server.tunnel._match_repo_name(path)
            assert repo_name == expected_match

    def test_run_returns_executes_command(self, svn_server):
        from rhodecode.apps.ssh_support.lib.backends.svn import SubversionTunnelWrapper

        server = svn_server.create()
        os.environ["SSH_CLIENT"] = "127.0.0.1"
        with mock.patch.object(
            SubversionTunnelWrapper, "get_first_client_response", return_value={"url": "http://server/test-svn"}
        ):
            with mock.patch.object(SubversionTunnelWrapper, "patch_first_client_response", return_value=0):
                with mock.patch.object(SubversionTunnelWrapper, "sync", return_value=0):
                    with mock.patch.object(SubversionTunnelWrapper, "command", return_value=["date"]):
                        exit_code = server.run(tunnel_extras={"config": server.ini_path})
        # SVN has this differently configured, and we get in our mock env
        # None as return code
        assert exit_code == (None, False)

    def test_run_returns_executes_command_that_cannot_extract_repo_name(self, svn_server):
        from rhodecode.apps.ssh_support.lib.backends.svn import SubversionTunnelWrapper

        server = svn_server.create()
        with mock.patch.object(SubversionTunnelWrapper, "command", return_value=["date"]):
            with mock.patch.object(SubversionTunnelWrapper, "get_first_client_response", return_value=None):
                exit_code = server.run(tunnel_extras={"config": server.ini_path})

        assert exit_code == (1, False)

    @pytest.mark.parametrize(
        "first_resp, expected_match",
        [
            (
                b"( 2 ( edit-pipeline svndiff1 accepts-svndiff2 absent-entries depth mergeinfo log-revprops ) 44:svn+ssh://rc@code.example.com/TestRepo/trunk 34:SVN/1.14.5 (x64-microsoft-windows) ( 24:TortoiseSVN-1.14.9.29743 ) )",
                {
                    "version": b"2",
                    "capabilities": b"edit-pipeline svndiff1 accepts-svndiff2 absent-entries depth mergeinfo log-revprops",
                    "url": b"svn+ssh://rc@code.example.com/TestRepo/trunk",
                    "ra_client": b"SVN/1.14.5 (x64-microsoft-windows)",
                    "client": b"TortoiseSVN-1.14.9.29743",
                },
            ),
            (
                b"( 2 ( edit-pipeline svndiff1 accepts-svndiff2 absent-entries depth mergeinfo log-revprops ) 44:svn+ssh://rc@code.example.com/TestRepo/trunk 34:SVN/1.14.5 (x64-microsoft-windows) ( ) )",
                {
                    "version": b"2",
                    "capabilities": b"edit-pipeline svndiff1 accepts-svndiff2 absent-entries depth mergeinfo log-revprops",
                    "url": b"svn+ssh://rc@code.example.com/TestRepo/trunk",
                    "ra_client": b"SVN/1.14.5 (x64-microsoft-windows)",
                    "client": None,
                },
            ),
        ],
    )
    def test__parse_first_client_response(self, svn_server, first_resp, expected_match):
        server = svn_server.create()
        tunnel = SubversionTunnelWrapper(server)
        parsed = tunnel._parse_first_client_response(first_resp)
        assert parsed == expected_match

    @pytest.mark.parametrize(
        "first_resp, expected_match",
        [
            (
                b"( 2 ( edit-pipeline svndiff1 accepts-svndiff2 absent-entries depth mergeinfo log-revprops ) 44:svn+ssh://rc@code.example.com/TestRepo/trunk 34:SVN/1.14.5 (x64-microsoft-windows) ( 24:TortoiseSVN-1.14.9.29743 ) ) ",
                None,
            ),
            (
                b"( 2 ( edit-pipeline svndiff1 accepts-svndiff2 absent-entries depth mergeinfo log-revprops ) 44:svn+ssh://rc@code.example.com/TestRepo/trunk 34:SVN/1.14.5 (x64-microsoft-windows) ( ) ) ",
                None,
            ),
        ],
    )
    def test__parse_and_prepare_first_client_response(self, svn_server, first_resp, expected_match):
        server = svn_server.create()
        tunnel = SubversionTunnelWrapper(server)
        parsed = tunnel._parse_first_client_response(first_resp)
        first_response_prepared = tunnel._prepare_first_client_response(parsed)

        assert first_response_prepared == first_resp
