#!/usr/bin/env python3

import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

from harness.environment import SCRATCHDIR
from harness.filesystem import rmtree
from harness.results import test_fail, test_skipped
from harness.rsync import (
    forced_protocol, rsync_argv, rsync_argv_for, rsync_command_binary, run_rsync, under_valgrind,
)
from harness import metadata

metadata(features={'search_only', 'setpriv'}, transports={'pipe'})

version = json.loads(run_rsync('-VV', check=True, capture_output=True).stdout)
search_only_dirs = version['capabilities']['search_only_dirs']

launcher = []
if os.geteuid() == 0:
    if not sys.platform.startswith('linux'):
        test_skipped('no non-root launcher on this platform', capability='setpriv')
    setpriv = shutil.which('setpriv')
    if setpriv is None:
        test_skipped('setpriv is unavailable for the root-run testsuite', capability='setpriv')
    launcher = [setpriv, '--reuid=65534', '--regid=65534', '--clear-groups']

external_base = os.geteuid() == 0
base = (
    Path(tempfile.mkdtemp(prefix='rsync-search-only-held-dirfd-'))
    if external_base
    else SCRATCHDIR / 'search-only-held-dirfd'
)
rmtree(base)

src = base / 'src'
xonly = src / 'xonly'
readable = xonly / 'readable'
nested_src = src / 'nested'
exact_dest = base / 'exact-dest'
tree_dest = base / 'tree-dest'
unreadable_dest = base / 'unreadable-dest'
write_only_dest = base / 'write-only-dest'
nested_dest = base / 'nested-dest'
nested_parent = nested_dest / 'nested'
search_parent = base / 'search-destination'
search_dest = search_parent / 'destination'
for path in (
    readable,
    nested_src,
    exact_dest,
    tree_dest,
    unreadable_dest,
    write_only_dest,
    nested_parent,
    search_dest,
):
    path.mkdir(parents=True, exist_ok=True)

(xonly / 'exact').write_text('known file beneath search-only parent\n')
(readable / 'nested').write_text('enumerated below search-only ancestor\n')
incoming = src / 'incoming'
incoming.write_text('created beneath write-search-only destination\n')
(nested_src / 'known').write_text(
    'created beneath nested write-search-only parent\n'
)

local_rsync = None
if launcher and under_valgrind():
    local_rsync = base / 'rsync-bin'
    shutil.copy2(rsync_command_binary(), local_rsync)
    local_rsync.chmod(0o755)
    os.chown(local_rsync, 65534, 65534)

def command(*args):
    return rsync_argv_for(local_rsync, *args) if local_rsync else rsync_argv(*args)

if os.geteuid() == 0:
    for root, dirs, files in os.walk(base):
        os.chown(root, 65534, 65534)
        for name in dirs + files:
            os.chown(Path(root) / name, 65534, 65534)

def permission_probe(path, flag, expected, label):
    proc = subprocess.run(
        launcher + ['test', flag, str(path)],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    if proc.returncode != expected:
        test_skipped(
            f'filesystem does not enforce {label}: test {flag} returned '
            f'{proc.returncode}, expected {expected}', capability='search_only'
        )

failures = []
try:
    xonly.chmod(0o111)
    write_only_dest.chmod(0o333)
    nested_parent.chmod(0o333)
    search_parent.chmod(0o111)

    permission_probe(xonly, '-r', 1, 'search-only mode')
    permission_probe(xonly, '-x', 0, 'search-only mode')
    permission_probe(write_only_dest, '-r', 1, 'write-search-only mode')
    permission_probe(write_only_dest, '-w', 0, 'write-search-only mode')
    permission_probe(write_only_dest, '-x', 0, 'write-search-only mode')
    permission_probe(nested_parent, '-r', 1, 'nested write-search-only mode')
    permission_probe(nested_parent, '-w', 0, 'nested write-search-only mode')
    permission_probe(nested_parent, '-x', 0, 'nested write-search-only mode')
    permission_probe(search_parent, '-r', 1, 'search-only destination parent')
    permission_probe(search_parent, '-x', 0, 'search-only destination parent')

    if not search_only_dirs:
        unsupported_cases = (
            ('mode 0111 destination parent',
             command('-t', str(incoming), f'{search_dest}/'),
             search_dest / 'incoming', None),
            ('mode 0333 destination',
             command('-t', str(incoming), f'{write_only_dest}/'),
             write_only_dest / 'incoming', None),
            ('known source beneath mode 0111 parent',
             command('-aR', '--chmod=Du+rw', 'xonly/exact', f'{exact_dest}/'),
             exact_dest / 'xonly' / 'exact', src),
        )
        for label, argv, result, cwd in unsupported_cases:
            proc = subprocess.run(
                launcher + argv,
                cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            if proc.returncode == 0 or result.exists():
                failures.append(f'{label} did not fail closed')
        if failures:
            test_fail('\n'.join(failures))
        test_skipped('kernel has no race-safe search-only directory descriptor',
                     capability='search_only')

    search_receiver = subprocess.run(
        launcher + command('-t', str(incoming), f'{search_dest}/'),
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    search_result = search_dest / 'incoming'
    search_content = search_result.read_text() if search_result.is_file() else None
    if search_receiver.returncode != 0 or search_content != (
            'created beneath write-search-only destination\n'):
        failures.append(
            'destination below mode 0111 parent failed: '
            f'rc={search_receiver.returncode}, stderr={search_receiver.stderr.strip()!r}, '
            f'content={search_content!r}')

    exact = subprocess.run(
        launcher + command(
            '-aR', '--chmod=Du+rw', 'xonly/exact', f'{exact_dest}/',
        ),
        cwd=src,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    exact_path = exact_dest / 'xonly' / 'exact'
    exact_content = exact_path.read_text() if exact_path.is_file() else None
    if exact.returncode != 0 or exact_content != (
        'known file beneath search-only parent\n'
    ):
        failures.append(
            'exact -R source beneath mode 0111 failed: '
            f'rc={exact.returncode}, stderr={exact.stderr.strip()!r}, '
            f'content={exact_content!r}'
        )

    tree = subprocess.run(
        launcher + command(
            '-aR', '--chmod=Du+rw', 'xonly/readable/', f'{tree_dest}/',
        ),
        cwd=src,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    tree_path = tree_dest / 'xonly' / 'readable' / 'nested'
    tree_content = tree_path.read_text() if tree_path.is_file() else None
    if tree.returncode != 0 or tree_content != (
        'enumerated below search-only ancestor\n'
    ):
        failures.append(
            'readable directory beneath mode 0111 ancestor failed: '
            f'rc={tree.returncode}, stderr={tree.stderr.strip()!r}, '
            f'content={tree_content!r}'
        )

    unreadable = subprocess.run(
        launcher + command(
            '-a', 'xonly/', f'{unreadable_dest}/',
        ),
        cwd=src,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    if unreadable.returncode == 0:
        failures.append(
            'mode 0111 source directory was enumerable without read permission'
        )

    receiver = subprocess.run(
        launcher + command(
            '-t', str(incoming), f'{write_only_dest}/',
        ),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    received = write_only_dest / 'incoming'
    received_content = received.read_text() if received.is_file() else None
    if receiver.returncode != 0 or received_content != (
        'created beneath write-search-only destination\n'
    ):
        failures.append(
            'known-file creation beneath mode 0333 destination failed: '
            f'rc={receiver.returncode}, stderr={receiver.stderr.strip()!r}, '
            f'content={received_content!r}'
        )

    proto = forced_protocol()
    if proto is None or proto >= 30:
        nested_receiver = subprocess.run(
            launcher + command(
                '-tR', '--no-implied-dirs', 'nested/known', f'{nested_dest}/',
            ),
            cwd=src,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )
        nested_received = nested_parent / 'known'
        nested_content = (
            nested_received.read_text() if nested_received.is_file() else None
        )
        if nested_receiver.returncode != 0 or nested_content != (
            'created beneath nested write-search-only parent\n'
        ):
            failures.append(
                'known-file creation beneath nested mode 0333 destination '
                f'failed: rc={nested_receiver.returncode}, '
                f'stderr={nested_receiver.stderr.strip()!r}, '
                f'content={nested_content!r}'
            )
finally:
    xonly.chmod(0o755)
    write_only_dest.chmod(0o755)
    nested_parent.chmod(0o755)
    search_parent.chmod(0o755)
    for dest in (exact_dest, tree_dest):
        copied_xonly = dest / 'xonly'
        if copied_xonly.is_dir():
            copied_xonly.chmod(0o755)
    if external_base:
        rmtree(base)

if failures:
    test_fail('\n'.join(failures))
