#!/usr/bin/env python3

import os
import re
import shutil
import subprocess
import sys

from harness.comparison import checkit
from harness.environment import CHKDIR, FROMDIR, SCRATCHDIR, TMPDIR, TODIR, TOOLDIR
from harness.filesystem import cp_touch, makepath
from harness.results import test_fail, test_skipped
from harness.rsync import run_rsync
from harness.xattrs import (
    RSYNC_PREFIX, RUSR, dump_values as xattr_dump, get_value as xattr_get,
    is_supported as xattrs_supported, set_value,
)
from harness import metadata

metadata(features={'xattr_runtime'}, transports={'pipe'})

if not xattrs_supported():
    test_skipped("Rsync is configured without xattr support (or no xattr "
                 "tooling on this platform)", capability='xattr_runtime')


def xset(name, value, *paths):
    # The directory comparisons also check timestamps. Keep them independent of the fixture xattrs.
    for path in paths:
        before = os.stat(path)
        set_value(name, value, path)
        os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns))


script_name = os.path.basename(sys.argv[0] if sys.argv[0] else __file__)
hlink_variant = 'hard-links' in script_name

lnkdir = TMPDIR / 'lnk'
makepath(lnkdir, FROMDIR / 'foo' / 'bar')

(FROMDIR / 'file0').write_text("now\n")
(FROMDIR / 'file1').write_text("something\n")
(FROMDIR / 'file2').write_text("else\n")
(FROMDIR / 'foo' / 'file3').write_text("deep\n")
(FROMDIR / 'file4').write_text("normal\n")
(FROMDIR / 'foo' / 'bar' / 'file5').write_text("deeper\n")

makepath(CHKDIR / 'foo')
(CHKDIR / 'file1').write_text("wow\n")
cp_touch(FROMDIR / 'foo' / 'file3', CHKDIR / 'foo')

dirs = ['foo', 'foo/bar']
files = ['file0', 'file1', 'file2', 'foo/file3', 'file4', 'foo/bar/file5']

tls_out = subprocess.check_output(
    [str(TOOLDIR / 'tls'), str(FROMDIR / 'foo')], text=True,
).strip()
m = re.search(r' (\d+)\.(\d+) ', tls_out)
if not m:
    test_fail(f"can't parse uid/gid from tls output: {tls_out!r}")
uid_gid = f"{m.group(1)}:{m.group(2)}"

os.chdir(FROMDIR)

try:
    xset('foo', 'foo', 'file0')
except OSError:
    test_skipped("Unable to set an xattr", capability='xattr_runtime')
if xattr_get('foo', 'file0') != b'foo':
    test_fail('Unable to read an xattr')
xset('bar', 'bar', 'file0')

xset('short', 'this is short', 'file1')
xset('long',
     'this is a long attribute that will be truncated in the initial data send',
     'file1')
xset('good', 'this is good', 'file1')
xset('nice', 'this is nice', 'file1')

xset('foo', 'foo', 'file2')
xset('bar', 'bar', 'file2')
xset('long',
     'a long attribute for our new file that tests to ensure that this works',
     'file2')

dir1_value = 'need to test directory xattrs too'
xset('dir1', dir1_value, 'foo')
xset('dir2', 'another xattr', 'foo')
xset('dir3', 'this is one last one for the moment', 'foo')

xset('dir4', 'another dir test', 'foo/bar')
xset('dir5', 'one last one', 'foo/bar')

xset('foo', 'new foo', 'foo/file3', 'foo/bar/file5')
xset('bar', 'new bar', 'foo/file3', 'foo/bar/file5')
xset('long',
     'this is also a long attribute that will be truncated in the initial data send',
     'foo/file3', 'foo/bar/file5')
xset(f'{RUSR}.equal',
     'this long attribute should remain the same and not need to be transferred',
     'foo/file3', 'foo/bar/file5')

xset('dir0', 'old extra value', CHKDIR / 'foo')
xset('dir1', 'x' * len(dir1_value), CHKDIR / 'foo')

xset('short', 'was different', CHKDIR / 'file1')
xset('extra', 'remove me', CHKDIR / 'file1')

xset('foo', 'old foo', CHKDIR / 'foo' / 'file3')
xset(f'{RUSR}.equal',
     'this long attribute should remain the same and not need to be transferred',
     CHKDIR / 'foo' / 'file3')

if hlink_variant:
    try:
        os.link(FROMDIR / 'foo' / 'bar' / 'file5', FROMDIR / 'foo' / 'bar' / 'file6')
    except OSError:
        test_skipped("Can't create hardlink")
    files.append('foo/bar/file6')
    dashH = ['-H']
    altDest = '--link-dest'
else:
    dashH = []
    altDest = '--copy-dest'

def _save_xattrs(paths, dest_file):
    dest_file.write_text(xattr_dump(*paths))

_save_xattrs(dirs + files, SCRATCHDIR / 'xattrs.txt')

XFILT = ['-f-x_system.*', '-f-x_security.*']

checkit(['-avX', *XFILT, *dashH, '--super', '.', f'{CHKDIR}/'], FROMDIR, CHKDIR)

os.chdir(CHKDIR)
got = xattr_dump(*(dirs + files))
expected = (SCRATCHDIR / 'xattrs.txt').read_text()
if got != expected:
    from difflib import unified_diff
    sys.stdout.write(''.join(unified_diff(
        expected.splitlines(keepends=True),
        got.splitlines(keepends=True),
        fromfile='expected', tofile='got',
    )))
    test_fail("xattr listing differs after simple -X copy")

os.chdir(FROMDIR)

if dashH:
    for fn in files:
        name = os.path.basename(fn)
        os.link(fn, lnkdir / name)

checkit(['-aiX', *XFILT, *dashH, '--super', f'{altDest}=../chk', '.', '../to'],
        FROMDIR, TODIR)

os.chdir(TODIR)
got = xattr_dump(*(dirs + files))
if got != expected:
    test_fail("xattr listing differs after --copy-dest / --link-dest copy")

if dashH:
    shutil.rmtree(lnkdir, ignore_errors=True)

os.chdir(FROMDIR)
shutil.rmtree(TODIR, ignore_errors=True)

xset('nice', 'changed nice', 'file1')

_save_xattrs(dirs + files, SCRATCHDIR / 'xattrs.txt')

checkit(['-aiX', *XFILT, *dashH, '--fake-super', '--link-dest=../chk', '.', '../to'],
        CHKDIR, TODIR)

os.chdir(TODIR)
got = xattr_dump(*(dirs + files))
expected = (SCRATCHDIR / 'xattrs.txt').read_text()
if got != expected:
    test_fail("xattr listing differs after --fake-super --link-dest copy")

if dashH:
    ls_to = SCRATCHDIR / 'ls-to'
    from harness.comparison import rsync_ls_lR
    ls_to.write_text(rsync_ls_lR(TODIR))
    one_link = []
    for line in ls_to.read_text().splitlines():
        if line.startswith('d') or not line.strip():
            continue
        cols = line.split()
        if len(cols) >= 4 and cols[3] == '1':
            one_link.append(line)
    other_one = [ln for ln in one_link if './file1' not in ln]
    if other_one:
        print("Missing hard links on:")
        print('\n'.join(other_one))
        test_fail("hardlink check failed")
    if not one_link:
        test_fail("Too many hard links on file1!")

os.chdir(CHKDIR)
os.chmod('.', 0o700)
for p in dirs + files:
    os.chmod(p, os.stat(p).st_mode & ~0o077)

xset('nice', 'changed nice', 'file1')
xset(f'{RSYNC_PREFIX}.%stat', f'40000 0,0 {uid_gid}', *dirs)
xset(f'{RSYNC_PREFIX}.%stat', f'100000 0,0 {uid_gid}', *files)

_save_xattrs(dirs + files, SCRATCHDIR / 'xattrs.txt')

os.chdir(FROMDIR)
shutil.rmtree(TODIR, ignore_errors=True)

checkit(['-aiX', *XFILT, *dashH, '--fake-super', '--chmod=a=', '.', '../to'],
        CHKDIR, TODIR)

os.chdir(TODIR)
got = xattr_dump(*(dirs + files))
expected = (SCRATCHDIR / 'xattrs.txt').read_text()
if got != expected:
    test_fail("xattr listing differs after --fake-super --chmod=a= copy")

os.chdir(FROMDIR)
shutil.rmtree(TODIR, ignore_errors=True)
shutil.rmtree(CHKDIR, ignore_errors=True)

run_rsync('-aX', 'file1', 'file2')
run_rsync('-aX', 'file1', 'file2', '../chk/')
run_rsync('-aX', '--del', '../chk/', '.')
run_rsync('-aX', 'file1', '../lnk/')
if dashH:
    os.link(CHKDIR / 'file1', lnkdir / 'extra-link')

_save_xattrs(['file1', 'file2'], SCRATCHDIR / 'xattrs.txt')

checkit(['-aiiX', *XFILT, *dashH, f'{altDest}=../lnk', '.', '../to'],
        CHKDIR, TODIR)

if dashH:
    (lnkdir / 'extra-link').unlink()

os.chdir(TODIR)
got = xattr_dump('file1', 'file2')
expected = (SCRATCHDIR / 'xattrs.txt').read_text()
if got != expected:
    test_fail("xattr listing differs after --link-dest=../lnk copy")

os.chdir(FROMDIR)
(TODIR / 'file2').unlink()

with open('file1', 'a') as f:
    f.write("extra\n")
run_rsync('-aX', '.', '../chk/')

checkit(['-aiiX', *XFILT, '.', '../to'], CHKDIR, TODIR)

os.chdir(TODIR)
got = xattr_dump('file1', 'file2')
if got != expected:
    test_fail("xattr listing differs after the final round")
