"""Observe what unlink changes, using only files created in a temporary directory."""

import argparse
import json
import os
import shutil
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory

FILE_BYTES = 8 * 1024 * 1024
OLD_TAIL = b"after unlink\n"
NEW_FILE = b"new\n"


def file_id(stat):
    return stat.st_dev, stat.st_ino


def inspect_stage(directory, open_file):
    stat = os.fstat(open_file.fileno())
    du = subprocess.check_output(["du", "-sk", str(directory)], text=True, timeout=10)
    return {
        "visible_names": sorted(path.name for path in directory.iterdir()),
        "link_count": stat.st_nlink,
        "size_bytes": stat.st_size,
        "allocated_512_byte_blocks": stat.st_blocks,
        "directory_du_kib": int(du.split()[0]),
    }


def lsof_probe(binary, descriptors, stat):
    command = [binary, "-nP", "-a", "-p", str(os.getpid()), "+L1", "-Ffi"]
    process = subprocess.run(command, text=True, capture_output=True, timeout=15)
    if process.returncode not in (0, 1) or (process.returncode == 1 and process.stderr):
        raise RuntimeError(f"lsof failed: {process.stderr.strip()}")
    expected_fds = {str(fd) for fd in descriptors}
    matches = {}
    current_fd = None
    for line in process.stdout.splitlines():
        if line.startswith("f"):
            current_fd = line[1:]
        elif line.startswith("i") and current_fd in expected_fds:
            matches[current_fd] = line[1:] == str(stat.st_ino)
    return {
        "exit_code": process.returncode,
        "expected_descriptors": len(expected_fds),
        "matching_inode_and_descriptor_count": sum(matches.values()),
    }


def run(directory, lsof):
    original = directory / "active.log"
    alias = directory / "other.log"
    stages = {}

    with original.open("x+b") as handle:
        payload = os.urandom(FILE_BYTES)
        handle.write(payload)
        handle.flush()
        os.fsync(handle.fileno())
        starting_stat = os.fstat(handle.fileno())
        stages["one_name"] = inspect_stage(directory, handle)

        os.link(original, alias)
        assert file_id(alias.stat()) == file_id(starting_stat)
        stages["two_hard_links"] = inspect_stage(directory, handle)

        original.unlink()
        assert not original.exists()
        assert file_id(alias.stat()) == file_id(starting_stat)
        stages["first_name_removed"] = inspect_stage(directory, handle)

        alias.unlink()
        stages["last_name_removed"] = inspect_stage(directory, handle)
        assert stages["last_name_removed"]["visible_names"] == []
        assert [stage["link_count"] for stage in stages.values()] == [1, 2, 1, 0]
        assert os.pread(handle.fileno(), 64, 0) == payload[:64]

        with original.open("xb") as replacement:
            replacement.write(NEW_FILE)
        assert file_id(original.stat()) != file_id(starting_stat)
        handle.seek(0, os.SEEK_END)
        handle.write(OLD_TAIL)
        handle.flush()
        assert original.read_bytes() == NEW_FILE
        stages["name_recreated_old_file"] = inspect_stage(directory, handle)

        with os.fdopen(os.dup(handle.fileno()), "rb") as duplicate:
            old_stat = os.fstat(handle.fileno())
            probe = lsof_probe(lsof, [handle.fileno(), duplicate.fileno()], old_stat) if lsof else None
            handle.close()
            duplicate.seek(-len(OLD_TAIL), os.SEEK_END)
            tail = duplicate.read()
            assert tail == OLD_TAIL
            assert os.fstat(duplicate.fileno()).st_nlink == 0
        assert duplicate.closed
        assert original.read_bytes() == NEW_FILE

    return {
        "stages": stages,
        "original_prefix_readable_after_unlink": True,
        "same_name_recreated_with_different_inode": True,
        "recreated_file_bytes": original.stat().st_size,
        "read_via_duplicate_after_original_closed": tail.decode("ascii").rstrip("\n"),
        "lsof_while_both_descriptors_open": probe,
    }


def check_symlink(directory):
    target = directory / "target"
    pointer = directory / "symbolic"
    target.write_text("target\n", encoding="ascii")
    pointer.symlink_to(target.name)
    with target.open("rb") as handle:
        before = os.fstat(handle.fileno()).st_nlink
        assert file_id(pointer.stat()) == file_id(target.stat())
        assert file_id(pointer.lstat()) != file_id(target.stat())
        target.unlink()
        after = os.fstat(handle.fileno()).st_nlink
        target_missing = not pointer.exists()
        link_still_present = pointer.is_symlink()
        assert (before, after, target_missing, link_still_present) == (1, 0, True, True)
    return {
        "target_link_count_with_symlink": before,
        "target_link_count_after_unlink": after,
        "symlink_still_present": link_still_present,
        "symlink_target_missing": target_missing,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--lsof", action="store_true", help="probe only this process")
    args = parser.parse_args()
    lsof = shutil.which("lsof") if args.lsof else None
    if args.lsof and lsof is None:
        parser.error("--lsof requires lsof on PATH")

    with TemporaryDirectory(prefix="gumi-unlink-") as temp:
        directory = Path(temp)
        result = run(directory, lsof)
        result["symlink_example"] = check_symlink(directory)
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
