#!/usr/bin/env python3
"""Demonstrate recovery of a single entry in a disposable shared directory."""

import argparse
import hashlib
import json
import multiprocessing
import os
import tempfile
from pathlib import Path

INTERRUPTED = 75
CONFLICT = 3
MANAGED = b"policy = application\n"
ADMIN = b"policy = administrator\n"


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def stage_and_stop(root):
    live = root / "shared" / "application.rule"
    journal = root / "journal"
    # Retain the very inode this disposable fixture created for the application.
    os.link(live, journal / "original.rule")
    with (journal / "intent.json").open("x", encoding="utf-8") as stream:
        json.dump({"entry": live.name, "sha256": digest(live)}, stream)
    # The active name disappears before there is a completion record.
    live.rename(journal / "withdrawn.rule")
    os._exit(INTERRUPTED)


def recover(root):
    journal = root / "journal"
    plan = json.loads((journal / "intent.json").read_text(encoding="utf-8"))
    require(plan["entry"] == "application.rule", "Unexpected journal entry")
    live = root / "shared" / "application.rule"
    original, withdrawn = journal / "original.rule", journal / "withdrawn.rule"
    require(original.samefile(withdrawn), "Withdrawn file differs from the retained inode")
    require(digest(withdrawn) == plan["sha256"], "Withdrawn contents changed")
    # Any new public entry belongs to a different observation. Leave it in place.
    if os.path.lexists(live):
        raise SystemExit(CONFLICT)
    receipt = journal / "complete"
    if not receipt.exists():
        with receipt.open("x", encoding="ascii") as stream:
            stream.write("complete\n")
    require(receipt.read_bytes() == b"complete\n", "Unexpected completion record")


def run_child(target, root):
    child = multiprocessing.get_context("spawn").Process(target=target, args=(root,))
    child.start()
    child.join()
    code = child.exitcode
    child.close()
    return code


def demonstrate(replace):
    with tempfile.TemporaryDirectory(prefix="single-entry-demo-") as temporary:
        root = Path(temporary)
        shared, journal = root / "shared", root / "journal"
        shared.mkdir()
        journal.mkdir(mode=0o700)
        live, admin = shared / "application.rule", shared / "administrator.rule"
        live.write_bytes(MANAGED)
        admin.write_bytes(ADMIN)
        admin.chmod(0o600)
        shared_stat, admin_stat = shared.stat(), admin.stat()

        require(run_child(stage_and_stop, root) == INTERRUPTED, "Expected the writer to stop")
        require(not live.exists() and not (journal / "complete").exists(), "Unexpected stop point")
        print("Writer stopped after withdrawal and before completion.")
        if replace:
            live.write_bytes(MANAGED)
            replacement = live.stat()
            require(not live.samefile(journal / "original.rule"), "Expected a distinct replacement")
            require(run_child(recover, root) == CONFLICT, "Expected a recovery conflict")
            require(not (journal / "complete").exists(), "Conflict incorrectly marked complete")
            require(os.path.samestat(replacement, live.stat()) and live.read_bytes() == MANAGED,
                    "Replacement changed")
            print("Recovery deferred. The same-content replacement remains unchanged.")
        else:
            require(run_child(recover, root) == 0, "Recovery failed")
            receipt = (journal / "complete").stat()
            require(run_child(recover, root) == 0, "Repeated recovery failed")
            require(os.path.samestat(receipt, (journal / "complete").stat()), "Receipt was replaced")
            require(not live.exists(), "Withdrawn entry returned")
            print("Recovery completed. A second run preserved the same receipt.")
        require(os.path.samestat(shared_stat, shared.stat()) and shared_stat.st_mode == shared.stat().st_mode,
                "Shared directory identity or permissions changed")
        require(os.path.samestat(admin_stat, admin.stat()) and admin_stat.st_mode == admin.stat().st_mode
                and admin.read_bytes() == ADMIN,
                "Administrator entry changed")
        print("Shared directory and administrator entry preserved.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--replacement", action="store_true",
                        help="create an independent file with the original name and bytes before recovery")
    demonstrate(parser.parse_args().replacement)
