#!/usr/bin/env python3

import os

from harness.environment import FROMDIR, TODIR
from harness.filesystem import assert_same, make_tree, makepath, rmtree
from harness.results import test_fail
from harness.rsync import run_rsync
from harness import metadata

metadata(transports={'pipe'})

src = FROMDIR
deep = os.path.join('d1', 'd2', 'd3', 'f3')

rmtree(src)
rmtree(TODIR)
make_tree(src, depth=3)
run_rsync('-a', f'{src}/', f'{TODIR}/')

(src / deep).write_text("new source content\n")
keep = "destination is newer - keep me\n"
(TODIR / deep).write_text(keep)
st = os.stat(src / deep)
os.utime(TODIR / deep, (st.st_atime, st.st_mtime + 100))

run_rsync('-a', '-u', f'{src}/', f'{TODIR}/')
if (TODIR / deep).read_text() != keep:
    test_fail("-u overwrote a destination file that was newer than the source")

os.utime(TODIR / deep, (st.st_atime, st.st_mtime - 100))
run_rsync('-a', '-u', f'{src}/', f'{TODIR}/')
assert_same(TODIR / deep, src / deep, label='-u updated an older dest file')

rmtree(src)
rmtree(TODIR)
makepath(src, TODIR)
(src / 'foo').write_text("regular source file\n")
os.symlink('/should/not/exist', TODIR / 'foo')
st = os.stat(src / 'foo')
os.utime(TODIR / 'foo', (st.st_atime, st.st_mtime + 100),
         follow_symlinks=False)
run_rsync('-a', '-u', f'{src}/', f'{TODIR}/')
if os.path.islink(TODIR / 'foo'):
    test_fail("-u skipped a source file over a newer destination symlink")
assert_same(TODIR / 'foo', src / 'foo',
            label='-u replaced a newer dest symlink with a regular file')

rmtree(src)
rmtree(TODIR)
makepath(src / 'd1' / 'd2' / 'd3')
(src / deep).write_text("now a regular file\n")
makepath(TODIR / 'd1' / 'd2' / 'd3' / 'f3')
(TODIR / 'd1' / 'd2' / 'd3' / 'f3' / 'occupant').write_text("blocker\n")

proc = run_rsync('-a', f'{src}/', f'{TODIR}/', check=False)
if proc.returncode == 0 and (TODIR / deep).is_file():
    test_fail("a non-empty directory was replaced by a file without --force")

run_rsync('-a', '--force', f'{src}/', f'{TODIR}/')
if not (TODIR / deep).is_file():
    test_fail("--force did not replace the directory with the file at depth")
assert_same(TODIR / deep, src / deep, label='--force replacement content')

print("update: -u keeps newer dest / updates older; --force replaces a dir at depth")
