#!/usr/bin/env python3

import os

from harness.comparison import assert_trees_equal
from harness.environment import SCRATCHDIR
from harness.filesystem import assert_not_exists, make_data_file, make_text_file, makepath, rmtree
from harness.results import test_fail
from harness.rsync import run_rsync
from harness import metadata

metadata(transports={'pipe'})

base = SCRATCHDIR / 'backup-incremental'
rmtree(base)
base.mkdir()

src = base / 'src'
backup_root = base / 'backup'
mirror = backup_root / 'home'
incr = backup_root / 'incremental' / 'home'
idir0 = incr / '0'
idir1 = incr / '1'
exclude_file = base / 'backup_excludes'
exclude_file.write_text("*.tmp\n")

def make_sparse(path, size=128 * 1024):
    with open(path, 'wb') as f:
        f.write(b'SPARSE-HEAD\n')
        f.seek(size - 4)
        f.write(b'END\n')

def build_src():
    rmtree(src)
    makepath(src / 'sub')
    make_text_file(src / 'file_a', lines=40)
    make_data_file(src / 'file_b', 8192)
    make_text_file(src / 'sub' / 'file_c', lines=30)
    make_data_file(src / 'sub' / 'file_d', 8192)
    os.symlink('file_a', src / 'link')
    make_sparse(src / 'sparse')

def is_empty(d):
    return not any(d.iterdir())

def backup_run(idir):
    rmtree(idir)
    makepath(idir)
    makepath(mirror)
    run_rsync('-a', '--sparse', f'--exclude-from={exclude_file}',
              '--delete', '--delete-excluded',
              '--backup', f'--backup-dir={idir}',
              f'{src}/', f'{mirror}/')

build_src()
backup_run(idir0)
assert_trees_equal(src, mirror, label='phase1 mirror')
if not is_empty(idir0):
    test_fail(f"phase1: backup dir {idir0} is not empty after the first run "
              f"(nothing should have been backed up): "
              f"{[p.name for p in idir0.iterdir()]}")

old_b = (mirror / 'file_b').read_bytes()
old_c = (mirror / 'sub' / 'file_c').read_bytes()

make_data_file(src / 'file_b', 9000)
(src / 'sub' / 'file_c').unlink()
make_text_file(src / 'newfile', lines=10)
stale = b"STALE-EXCLUDED-CONTENT\n"
(mirror / 'stale.tmp').write_bytes(stale)

backup_run(idir1)

assert_trees_equal(src, mirror, label='phase2 mirror')

if (idir1 / 'file_b').read_bytes() != old_b:
    test_fail("phase2: overwritten file_b was not backed up with its old content "
              f"into {idir1}/file_b")
if (idir1 / 'sub' / 'file_c').read_bytes() != old_c:
    test_fail("phase2: deleted sub/file_c was not backed up at its relative path "
              f"into {idir1}/sub/file_c")
if not (idir1 / 'stale.tmp').exists() or (idir1 / 'stale.tmp').read_bytes() != stale:
    test_fail("phase2: --delete-excluded removal of stale.tmp was not captured by "
              f"--backup into {idir1}/stale.tmp")
assert_not_exists(idir1 / 'newfile', label='phase2: new file must not be backed up')
assert_not_exists(idir1 / 'file_a', label='phase2: unchanged file must not be backed up')
if not is_empty(idir0):
    test_fail(f"phase2: the previous slot {idir0} was disturbed by this run "
              "(each run's backup dir must be independent)")

backup_run(idir0)
assert_trees_equal(src, mirror, label='phase3 mirror')
if not is_empty(idir0):
    test_fail(f"phase3: a no-change run backed something up into {idir0}: "
              f"{[p.name for p in idir0.iterdir()]}")

print("incremental --backup/--backup-dir round-trip: mirror tracks source and "
      "each run's backup dir captures exactly the overwritten/deleted files")
