#!/usr/bin/env python3

from harness.daemon_config import write_daemon_conf
from harness.daemon import start_test_daemon
from harness.environment import SCRATCHDIR
from harness.filesystem import assert_same, makepath, rmtree
from harness.results import test_fail
from harness.rsync import run_rsync
from harness import metadata

metadata(transports={'pipe', 'tcp'})

base = SCRATCHDIR / 'daemon-copy-links'
module = base / 'module'
destination = base / 'destination'
dirlinks = base / 'dirlinks'
rmtree(base)
makepath(module / 'real-dir', destination, dirlinks)
(module / 'real-file').write_text('file target\n')
(module / 'real-dir' / 'nested').write_text('directory target\n')
(module / 'file-link').symlink_to('real-file')
(module / 'dir-link').symlink_to('real-dir')

config = write_daemon_conf([('module', {'path': str(module), 'read only': 'yes'})])
url = start_test_daemon(config, 12935)
run_rsync('-aL', f'{url}module/', f'{destination}/')

for link, target in (('file-link', 'real-file'), ('dir-link/nested', 'real-dir/nested')):
    result = destination / link
    if not result.is_file() or result.is_symlink():
        test_fail(f'{link} was not copied as a regular file')
    assert_same(result, module / target, label=link)

run_rsync('-ak', f'{url}module/', f'{dirlinks}/')
if (dirlinks / 'dir-link').is_symlink() or not (dirlinks / 'file-link').is_symlink():
    test_fail('--copy-dirlinks should replace only the directory symlink')
assert_same(dirlinks / 'dir-link' / 'nested', module / 'real-dir' / 'nested', label='dir-link')
