#!/usr/bin/env python3
# summary: Open removable drives when they arrive.
"""starchaser automount: open USB drives as they're plugged in, ready in Files.

    starchaser automount watch     (the starchaser automount user service) mount each removable drive that arrives
                                   and say "<name> is ready", with Open to show it in Files
    starchaser automount status    JSON: every drive and partition the computer sees now, and what plugging it in
                                   would do ("mount", "ask" or "leave", and why)

Only removable drives open by themselves: USB sticks and disks, memory cards, disk images you open. The computer's
own disks never do, and a locked (encrypted) drive asks for its password in Files instead of opening.
"""
# Decided 2026-11-09 #52. The facts are UDisks2's, the same ones Files' Devices list reads: a drive mounts when
# UDisks2 marks it for automounting (HintAuto) and not as part of the system (HintSystem), and its drive is
# removable, on USB, an SD card, or a disk image this account set up. udisksctl mounts it as this account, under
# /run/media/<user>/, so Files lists it at once. Eligible drives present at sign-in mount quietly too (decision #58).
import json
import os
import subprocess
import sys
import threading
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import command_usage_error, safe_streams
safe_streams()

UDISKS = "org.freedesktop.UDisks2"
BLOCK = UDISKS + ".Block"
FILESYSTEM = UDISKS + ".Filesystem"
DRIVE = UDISKS + ".Drive"
LOOP = UDISKS + ".Loop"
REMOVABLE_BUSES = ("usb", "sdio", "ieee1394")
# what a failed read of UDisks2's objects raises
READ_ERRORS = (OSError, subprocess.SubprocessError, ValueError, KeyError, IndexError)


def unwrap(value):
    """busctl's JSON wraps every D-Bus variant as {"type": ..., "data": ...}; byte strings come as lists of ints."""
    if isinstance(value, dict) and set(value) == {"type", "data"}:
        kind, data = value["type"], value["data"]
        if kind == "ay":
            return bytes(data).rstrip(b"\0").decode("utf-8", "replace")
        if kind == "aay":
            return [bytes(item).rstrip(b"\0").decode("utf-8", "replace") for item in data]
        return unwrap(data)
    if isinstance(value, dict):
        return {key: unwrap(item) for key, item in value.items()}
    if isinstance(value, list):
        return [unwrap(item) for item in value]
    return value


def managed_objects() -> dict:
    """UDisks2's objects: {object path: {interface: {property: value}}}."""
    out = subprocess.run(["busctl", "--system", "--json=short", "call", UDISKS, "/org/freedesktop/UDisks2",
                          "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"],
                         capture_output=True, text=True, timeout=10, check=True).stdout
    data = json.loads(out)["data"]
    return unwrap(data[0] if isinstance(data, list) else data)


def decide(objects: dict, path: str, uid: int) -> tuple:
    """What plugging in this block device does: ("mount" | "ask" | "leave", why)."""
    ifaces = objects.get(path, {})
    block = ifaces.get(BLOCK)
    if block is None:
        return "leave", "not a drive"
    if block.get("HintIgnore"):
        return "leave", "hidden"
    loop = ifaces.get(LOOP)
    drive = objects.get(block.get("Drive", "/"), {}).get(DRIVE, {})
    if loop is not None:
        # UDisks2 marks every loop device a system one that doesn't open by itself; one this account set up is the
        # disk image the person just opened, so that is what counts
        if loop.get("SetupByUID") != uid:
            return "leave", "a disk image someone else opened"
    else:
        if block.get("HintSystem", True):
            return "leave", "the computer's own disk"
        if not (drive.get("Removable") or drive.get("MediaRemovable")
                or drive.get("ConnectionBus") in REMOVABLE_BUSES):
            return "leave", "the computer's own disk"
        if not block.get("HintAuto", False):
            return "leave", "not marked to open by itself"
    if block.get("CryptoBackingDevice", "/") != "/":
        return "leave", "unlocked by hand"
    if block.get("IdUsage") == "crypto":
        return "ask", "locked"
    if FILESYSTEM not in ifaces or block.get("IdUsage") != "filesystem":
        return "leave", "nothing to open"
    if ifaces[FILESYSTEM].get("MountPoints"):
        return "leave", "already open"
    return "mount", "removable"


def name_of(objects: dict, path: str) -> str:
    """What the drive is called: its label, else its drive's maker and model, else what it is."""
    block = objects.get(path, {}).get(BLOCK, {})
    drive = objects.get(block.get("Drive", "/"), {}).get(DRIVE, {})
    for name in (block.get("IdLabel"), block.get("HintName"),
                 " ".join(part for part in (drive.get("Vendor", "").strip(), drive.get("Model", "").strip()) if part)):
        if name and name.strip():
            return name.strip()
    return "Disk image" if LOOP in objects.get(path, {}) else "USB drive"


def notify(*args, wait=False) -> str:
    command = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Files", "-i", "drive-removable-media", *args]
    if not wait:
        subprocess.run(command, capture_output=True, text=True)
        return ""
    return subprocess.run(command, capture_output=True, text=True).stdout.strip()


def offer_open(name: str, folder: str) -> None:
    """The "ready" notice; Open shows the drive in Files (its folder, or Files itself when that couldn't be read). It
    waits for the answer on its own thread."""
    config = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'starchaser/backup.json'
    try:
        configured = bool(json.loads(config.read_text()).get('uuid'))
    except (OSError, ValueError):
        configured = False
    actions = ['-A', 'open=Open', '-A', 'eject=Eject'] + ([] if configured else ['-A', 'backup=Back up to this drive'])
    answer = notify(*actions, f"{name} is ready", "Find it in Files, under Devices.", wait=True)
    if answer == "eject":
        subprocess.Popen(["starchaser", "files", "tools", "eject-folder", folder] if folder else ["starchaser", "files", "tools", "drives"], start_new_session=True)
    elif answer == 'open':
        subprocess.Popen(["starchaser", "files", *([folder] if folder else [])], stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)
    elif answer == 'backup' and not configured:
        subprocess.Popen(['starchaser', 'settings', 'backups', name], stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)


def mount_points(objects: dict, path: str) -> list:
    return [m for m in objects.get(path, {}).get(FILESYSTEM, {}).get("MountPoints", []) if m]


def session_unlocked() -> bool:
    """Fail closed if logind cannot confirm the graphical session is unlocked."""
    try:
        # A user service has no session of its own; an SSH caller's session may also be
        # unlocked while the desktop is locked. Always ask the account's graphical session.
        session = subprocess.run(["loginctl", "show-user", str(os.getuid()), "--property=Display", "--value"],
                                 capture_output=True, text=True, timeout=5, check=True).stdout.strip()
        if not session:
            return False
        answer = subprocess.run(["loginctl", "show-session", session, "--property=LockedHint", "--value"],
                                capture_output=True, text=True, timeout=5, check=True)
        return answer.stdout.strip() == "no"
    except (OSError, subprocess.SubprocessError):
        return False


def explicit_usb_open(objects, path, uid):
    """Consume the permission card's Open intent, matching the device serial or USB port."""
    import re
    block = objects.get(path, {}).get(BLOCK, {})
    drive = objects.get(block.get("Drive", "/"), {}).get(DRIVE, {})
    serial = drive.get("Serial", "")
    device = Path(block.get("Device", "")).name
    native = Path('/sys/class/block', device).resolve()
    ports = {part for part in native.parts if re.fullmatch(r"[0-9]+-[0-9]+(?:\.[0-9]+)*", part)}
    folder = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{uid}")) / "starchaser-drive-open"
    for marker in folder.glob("*.json"):
        try:
            intent = json.loads(marker.read_text())
            if time.time() - intent["created"] > 90:
                marker.unlink(missing_ok=True)
                continue
            if (serial and serial == intent.get("serial")) or intent.get("port") in ports:
                marker.unlink()
                return True
        except (OSError, ValueError, KeyError, TypeError):
            continue
    return False


def mount(objects: dict, path: str, uid: int, announce=True):
    """Mount a drive that arrived and say "<name> is ready". UDisks2 is asked again right before and right after:
    Files may have opened it first (open already is ready, as Files' own mount says), it may be gone, and where it
    is open is its Filesystem.MountPoints, never udisksctl's message (translated, and a folder can end in periods)."""
    if not session_unlocked():
        return False
    block = objects[path][BLOCK]
    device, name = block.get("Device", ""), name_of(objects, path)
    try:
        now = managed_objects()
    except READ_ERRORS:
        now = objects
    what, why = decide(now, path, uid)
    if what != "mount" and why != "already open":
        return
    # Refreshing UDisks may block across a session lock. Recheck after it, with no
    # device reads between the lock check and udisksctl; False keeps the arrival pending.
    if not session_unlocked():
        return False
    error = ""
    if what == "mount":
        try:
            result = subprocess.run(["udisksctl", "mount", "--no-user-interaction", "-b", device],
                                    capture_output=True, text=True, timeout=60)
            error = result.stderr.strip() if result.returncode else ""
        except (OSError, subprocess.SubprocessError):
            error = "The drive did not answer in time. Try opening it in Files."
    try:
        after = managed_objects()
    except READ_ERRORS as e:
        # mounted, but where can't be read: Open shows Files, which lists it under Devices
        if not error:
            if not session_unlocked():
                return False
            if announce:
                threading.Thread(target=offer_open, args=(name, ""), daemon=True).start()
            return
        after, error = {}, f"{error}; couldn't read the drives: {e}"
    # Mounting and the final object read can span a lock. Keep the arrival
    # pending so notices and an explicit Open happen only after unlock.
    if not session_unlocked():
        return False
    folders = mount_points(after, path)
    if folders:
        if explicit_usb_open(after, path, uid):
            subprocess.Popen(["starchaser", "files", folders[0]], start_new_session=True)
            return
        if announce:
            threading.Thread(target=offer_open, args=(name, folders[0]), daemon=True).start()
        return
    if after and path not in after:
        print(f"starchaser automount: {device} was unplugged before it opened", file=sys.stderr)
        return
    print(f"starchaser automount: {device} did not mount: {error or 'no mount point'}", file=sys.stderr)
    notify(f"{name} couldn't be opened", "Try it from Devices in Files.")


def ask(objects: dict, path: str) -> None:
    name = name_of(objects, path)

    def asking():
        # GIO's volume operation owns the password field and keyring choice in one card.
        subprocess.run(["starchaser", "files", "tools", "unlock-drive", objects[path][BLOCK].get("Device", "")])
    threading.Thread(target=asking, daemon=True).start()


def arrivals(seen: set, objects: dict) -> list:
    """The block devices that arrived since the last read, in path order; `seen` becomes what is there now. A
    device counts again when it gains something to open: a card put in a reader, a partition probed after it."""
    now = {(path, ifaces[BLOCK].get("IdUsage", ""), FILESYSTEM in ifaces)
           for path, ifaces in objects.items() if BLOCK in ifaces}
    new = sorted({key[0] for key in now - seen})
    seen.clear()
    seen.update(now)
    return new


# A new device is probed after it appears, so "nothing to open yet" is asked again for this long.
PROBE = 10.0


def settle(pending: dict, objects: dict, uid: int, now: float) -> list:
    """(path, "mount" | "ask") for each pending arrival that is decided; the rest wait until PROBE runs out."""
    out = []
    for path, since in sorted(list(pending.items())):
        what, why = decide(objects, path, uid)
        if what != "leave" or why != "nothing to open" or path not in objects or now - since >= PROBE:
            del pending[path]
            # Only arrivals enter pending. An eligible one Files already mounted still needs the ready/Open
            # notice; mount() reads its MountPoints without asking UDisks2 to mount it again.
            if why == "already open":
                out.append((path, "mount"))
            elif what != "leave":
                out.append((path, what))
    return out


def watch() -> None:
    """Compatibility entry: join the sole arrival owner, never start a second one."""
    subprocess.run(["systemctl", "--user", "start", "starchaser-usb.service"], check=True)


def status() -> list:
    objects, uid = managed_objects(), os.getuid()
    rows = []
    for path in sorted(p for p, ifaces in objects.items() if BLOCK in ifaces):
        what, why = decide(objects, path, uid)
        rows.append({"device": objects[path][BLOCK].get("Device", ""), "name": name_of(objects, path),
                     "plugIn": what, "why": why})
    return rows


def main(argv: list) -> None:
    if any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__)
        sys.exit(0)
    commands = {"watch": ("watch", (), ()), "status": ("status", (), ())}
    if len(argv) != 1 or argv[0] not in commands:
        sys.exit(command_usage_error("starchaser automount", argv, commands))
    if argv[0] == "watch":
        watch()
        return
    try:
        print(json.dumps(status()))
    except (OSError, subprocess.SubprocessError, ValueError, KeyError, IndexError):
        print("Couldn't read the drives. Try again.", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]):
        print(__doc__)
        sys.exit(0)
    main(sys.argv[1:])
