#!/usr/bin/env python3
# summary: Manage protection for newly connected USB devices.
"""starchaser usb: USB device protection (Settings > Privacy). New devices wait for your OK.

    starchaser usb watch           (the starchaser usb user service) turn the protection's decisions into notifications:
                                   a new device that's held back asks "Allow for now / Always allow / Keep blocked /
                                   Always block"; a new
                                   keyboard or mouse (let in at the Relaxed level) says so, so a fake one can't hide
    starchaser usb ask <id>        show the existing Allow for now / Always allow question again
    starchaser usb helper-status   check whether USB questions can appear (JSON, read-only)
    starchaser usb fix-questions   restart the USB question helper and confirm it is running
    starchaser usb status          JSON for Settings > Privacy: level, devices plugged in now (each with "how" an
                                   allowed one works: remembered, relaxed or once), devices remembered (pluggedIn)
    starchaser usb allow <id> [--always]   let a held-back device in (now, or now and from now on)
    starchaser usb forget <rule id>        stop remembering a device (it waits for you next time it's plugged in)
    starchaser usb block <id> [--always]   switch off a device, until it's unplugged (or every time it's plugged in)
    starchaser usb unblock <rule id>       stop always blocking a device (plugged in again, it's treated as new)

Every USB protection change asks for an administrator password.
"""
# Read-only USBGuard access is available to every account. Changes use the narrow root helper.
import json
import os
import pty
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
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()


WATCHING = False


def session_change(args, timeout=120, admin_command="usb-device"):
    """Notification actions originate in a user service. Run the password request in the desktop's login session."""
    runtime = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
    with tempfile.TemporaryDirectory(prefix="starchaser-usb-change-", dir=runtime) as folder:
        base = Path(folder)
        command = shlex.join(["pkexec", "/usr/local/lib/starchaser/starchaser-admin", admin_command, *args])
        script = ('cat "/proc/$$/stat" >' + shlex.quote(str(base / "process.new"))
                  + "; mv " + shlex.quote(str(base / "process.new")) + " " + shlex.quote(str(base / "process")) + "; "
                  + command + " >" + shlex.quote(str(base / "out")) + " 2>" + shlex.quote(str(base / "err"))
                  + "; code=$?; printf '%s' \"$code\" >" + shlex.quote(str(base / "code.new"))
                  + "; mv " + shlex.quote(str(base / "code.new")) + " " + shlex.quote(str(base / "code")))
        launcher = "sh -c " + shlex.quote(script)
        result = subprocess.run(["hyprctl", "dispatch", "hl.dsp.exec_cmd(" + json.dumps(launcher, ensure_ascii=False) + ")"],
                                capture_output=True, text=True, timeout=10)
        if result.returncode or "error" in (result.stdout + result.stderr).lower():
            return subprocess.CompletedProcess(args, 1, "", "Open Settings > Privacy to change this device.")
        deadline = time.monotonic() + timeout
        while True:
            if (base / "code").exists():
                try:
                    return subprocess.CompletedProcess(args, int((base / "code").read_text()),
                                                       (base / "out").read_text(), (base / "err").read_text())
                except (ValueError, OSError):
                    break
            try:
                # The startup deadline must not expire a live password conversation. Pin the
                # launcher's PID and start time so a dead or reused process cannot keep it pending.
                started = (base / "process").read_text()
            except FileNotFoundError:
                if time.monotonic() >= deadline:
                    break
            else:
                try:
                    pid = int(started.split(" ", 1)[0])
                    before = started.rsplit(")", 1)[1].split()
                    current = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
                    if current[0] == "Z" or current[19] != before[19]:
                        break
                except (ValueError, OSError, IndexError):
                    break
            time.sleep(0.1)
        # The launcher may publish its result and exit between the first check and the
        # process read. Prefer that completed result over a guessed startup failure.
        try:
            return subprocess.CompletedProcess(args, int((base / "code").read_text()),
                                               (base / "out").read_text(), (base / "err").read_text())
        except (ValueError, OSError):
            return subprocess.CompletedProcess(args, 1, "", "The password request did not finish. Try Settings > Privacy.")


def ug(*args, timeout=10) -> subprocess.CompletedProcess:
    if WATCHING and args and args[0] in ("allow-device", "block-device", "remove-rule", "allow-group"):
        return session_change(args)
    command = (["pkexec", "/usr/local/lib/starchaser/starchaser-admin", "usb-device", *args]
               if args and args[0] in ("allow-device", "block-device", "remove-rule", "allow-group") else ["usbguard", *args])
    # The hardware query deadline must not kill a password prompt while someone
    # types slowly or uses the on-screen keyboard. Polkit owns that conversation.
    return subprocess.run(command, capture_output=True, text=True, timeout=None if command[0] == "pkexec" else timeout)


def field(rule: str, key: str) -> str:
    m = re.search(rf'{key} "((?:[^"\\]|\\.)*)"', rule)
    return m.group(1) if m else ""


def interfaces(rule: str) -> list:
    m = re.search(r"with-interface (?:one-of |all-of )?\{ ([^}]*) \}|with-interface ([0-9a-f:]+)", rule)
    return (m.group(1) or m.group(2) or "").split() if m else []


USB_SYSFS = Path("/sys/bus/usb/devices")
USB_RUN = Path("/run/user")


def remember_once(number: str, remove=False) -> None:
    """Keep an explicit approval across a protection-level restart, only for this physical connection.
    /run disappears at reboot; the sysfs inode and device number change when the device is unplugged."""
    try:
        result = ug("list-devices")
        if result.returncode:
            return
        rule = next((line for line in (result.stdout or "").splitlines() if line.startswith(number + ": ")), "")
        port, digest = field(rule, "via-port"), field(rule, "hash")
        if not re.fullmatch(r"[0-9]+-[0-9]+(?:\.[0-9]+)*", port) or not digest:
            return
        folder = USB_RUN / str(os.getuid()) / "starchaser-usb-once"
        path = folder / port
        if remove:
            path.unlink(missing_ok=True)
            return
        device = USB_SYSFS / port
        token = [digest, device.stat().st_ino, device.joinpath("devnum").read_text().strip()]
        folder.mkdir(mode=0o700, parents=True, exist_ok=True)
        path.write_text(json.dumps(token))
    except (OSError, subprocess.SubprocessError):
        pass  # USBGuard still owns the actual approval; a failed record cannot allow another device.


def kind(rule: str) -> str:
    """What a device is, in words, from its USB interface classes."""
    classes = {i.split(":")[0] for i in interfaces(rule)}
    hid = interfaces(rule)
    if "03" in classes:
        name = field(rule, "name").lower()
        if any(i in ("03:01:01", "03:00:01") for i in hid):
            hid_name = "keyboard"
        elif any(i in ("03:01:02", "03:00:02") for i in hid):
            hid_name = "mouse"
        elif any(word in name for word in ("security key", "yubikey", "fido")):
            hid_name = "security key"
        elif any(word in name for word in ("gamepad", "game controller", "joystick")):
            hid_name = "game controller"
        else:
            hid_name = "input device"
    else:
        hid_name = "input device"
    names = {"03": hid_name, "08": "storage drive", "02": "network adapter", "0a": "network adapter",
             "e0": "wireless adapter", "0e": "camera", "01": "audio device", "07": "printer", "06": "camera or phone",
             "09": "USB hub", "0b": "smart card reader", "ff": "device"}
    found = [names[c] for c in sorted(classes) if c in names and c != "ff"]
    return " and ".join(dict.fromkeys(found)) or "USB device"


def icon(rule: str) -> str:
    """The approval popup's icon: a keyboard for keyboards and mice, a drive for storage, a neutral USB plug otherwise."""
    classes = {i.split(":")[0] for i in interfaces(rule)}
    if "08" in classes:
        return "drive-removable-media"
    if "03" in classes:
        return "input-keyboard"
    if "e0" in classes or "02" in classes:
        return "network-wired"
    return "drive-removable-media"


def same_device(rule: str) -> list:
    """notify-send arguments that make this device's newest notice replace its older ones in the bell (the "new
    keyboard" card, "blocked", "allow it?"): one notice per device, so none says blocked once it's allowed (QA 2026-11-04)"""
    h = field(rule, "hash")
    return ["-h", f"string:x-canonical-private-synchronous:starchaser-usb-{h}"] if h else []


def label(rule: str) -> str:
    name = field(rule, "name").strip()
    vid = re.search(r"\bid ([0-9a-f]{4}:[0-9a-f]{4})", rule)
    return name or (f"USB device {vid.group(1)}" if vid else "A USB device")


# the Relaxed level's own class rules, as USBGuard lists them (keep in step with RELAXED_OWN in starchaser-admin)
RELAXED_OPEN = ("allow with-interface all-of { 03:01:02 }", "allow with-interface all-of { 03:*:* }", "allow with-interface all-of { 09:*:* }",
                "allow with-interface all-of { 08:*:* }", "allow with-interface all-of { 06:01:01 }",
                "allow with-interface all-of { ff:ff:00 }", "allow with-interface all-of { ff:42:01 }")


def relaxed_rule_ids() -> set:
    out = ug("list-rules").stdout
    return {int(m.group(1)) for m in re.finditer(r"^(\d+): allow with-interface all-of \{ 0[39]:\*:\* \}", out, re.M)}


def relaxed_classes(rules: str) -> set:
    """Which of the Relaxed level's two rules (keyboards and mice "03", hubs "09") the rule list holds."""
    return set(re.findall(r"^\d+: allow with-interface all-of \{ (0[39]):\*:\* \}", rules or "", re.M))


def relaxed_now() -> set:
    """relaxed_classes() of the running rules; none when they can't be read."""
    try:
        r = ug("list-rules")
        return set() if r.returncode else relaxed_classes(r.stdout)
    except (OSError, subprocess.SubprocessError):
        return set()


def keep_relaxed(before: set) -> None:
    """Compatibility for old callers; the root device helper preserves its own protection rules."""
    return


def always_blocked(rules: str = None) -> dict:
    """Always block choices: block rule numbers by device hash. USBGuard's block-device -p writes a rule with the
    device's id, serial and hash, and no port, so the device is blocked in any socket. Empty when the rules can't
    be read, so a failed read never hides a question."""
    if rules is None:
        try:
            r = ug("list-rules")
            rules = "" if r.returncode else r.stdout
        except (OSError, subprocess.SubprocessError):
            rules = ""
    found = {}
    for m in re.finditer(r"^(\d+): (block .*)$", rules or "", re.M):
        if field(m.group(2), "hash"):
            found.setdefault(field(m.group(2), "hash"), int(m.group(1)))
    return found


def block_device(dev_id: str, always: bool) -> bool:
    """Block a device until it's unplugged, or always (block-device -p, which takes over the rule that let it in,
    such as Relaxed's "keyboards always work", so keep_relaxed puts that one back)."""
    before = relaxed_now() if always else set()
    r = ug("block-device", *(["-p"] if always else []), dev_id)
    if always and r.returncode == 0:
        keep_relaxed(before)
    return r.returncode == 0


def notify(*args) -> str:
    r = subprocess.run([*['/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", "Starchaser", *args], capture_output=True, text=True)
    return r.stdout.strip()


# The "allow it?" cards, by device number. Leaving the blocked state retires the card and its actions,
# whether the device was unplugged, approved in Settings, or changed by a protection-level switch.
asking = {}
gone = {}                   # removed id -> monotonic time; USBGuard may reuse an id
locked_arrivals = set()
pending = set()             # asks that have started but may not have a notification id yet
pending_removed = set()     # an old ask is still closing when USBGuard reuses its id
reask = {}
you_blocked = set()         # blocked with the "new keyboard" notice's Block it: no "allow it?" until it's unplugged
# the Relaxed level's "new keyboard or mouse" notices, by device number: closed when the device is unplugged or
# blocked, so its OK never sits above the "allow it?" of the same keyboard plugged in again (QA 20261104-0025 001)
input_cards = {}
blocked_cards = {}          # the "keyboard blocked" notices that follow Block it, with Undo: closed when it's unplugged
asking_lock = threading.Lock()
# blocked from Settings (starchaser usb block, another process): one empty file per device number, so the watch
# doesn't ask "allow it?" about a device you just switched off; removed when it's unplugged
BLOCKED_DIR = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-usb-blocked"


def settings_blocked(dev_id: str) -> bool:
    return bool(dev_id) and (BLOCKED_DIR / dev_id).exists()


def settings_unblocked(dev_id: str = "") -> None:
    """Forget a Settings block (one device that was unplugged, or every one when the daemon renumbers)."""
    for f in [BLOCKED_DIR / dev_id] if dev_id else (BLOCKED_DIR.glob("*") if BLOCKED_DIR.is_dir() else []):
        try:
            f.unlink()
        except OSError:
            pass


def close_card(nid: str) -> None:
    # never lets an error out: this runs on the watch loop's own thread, and a raise there ended the watch
    try:
        subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.Notifications",
                        "--object-path", "/org/freedesktop/Notifications",
                        "--method", "org.freedesktop.Notifications.CloseNotification", nid],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
    except (OSError, subprocess.SubprocessError):
        pass


def trim_gone() -> None:
    # Caller holds asking_lock. Keep late-card protection briefly, not for the lifetime of the watcher.
    now = time.monotonic()
    for dev in list(gone):
        if now - gone[dev] > 60:
            gone.pop(dev, None)


def present(dev_id: str) -> None:
    with asking_lock:
        trim_gone()
        gone.pop(dev_id, None)


def queue_ask(dev_id: str, rule: str, seen: bool = True) -> None:
    if Path("/run/starchaser/usb-locked").exists():
        locked_arrivals.add(dev_id)
        return  # reconcile asks after unlocking; no question over the password screen
    if field(rule, "hash") and field(rule, "hash") in always_blocked():
        return                                  # you chose Always block: nothing to ask
    with asking_lock:
        trim_gone()
        if (not seen and dev_id in gone) or dev_id in you_blocked or settings_blocked(dev_id):
            return
        if seen:
            gone.pop(dev_id, None)
        if dev_id in pending_removed:
            reask[dev_id] = rule
            return
        if not dev_id or dev_id in asking or dev_id in pending:
            return
        pending.add(dev_id)

    def work():
        try:
            ask(dev_id, rule)
        finally:
            with asking_lock:
                pending.discard(dev_id)
                pending_removed.discard(dev_id)
                again = reask.pop(dev_id, None)
                if dev_id in gone:
                    again = None
            if again is not None:
                queue_ask(dev_id, again, seen=False)
    try:
        threading.Thread(target=work, daemon=True).start()
    except RuntimeError:
        with asking_lock:
            pending.discard(dev_id)
        raise


def reconcile() -> None:
    """After connecting, retire stale cards and recover blocked questions missed while disconnected."""
    try:
        r = ug("list-devices")
        if r.returncode == 0:
            blocked = {m.group(1): m.group(2) for m in re.finditer(r"^(\d+): block (.*)$", r.stdout, re.M)}
            with asking_lock:
                stale = (set(asking) | pending | set(reask)) - blocked.keys()
            for dev_id in stale:
                unplugged(dev_id)
            for dev_id, rule in blocked.items():
                queue_ask(dev_id, rule)
    except (OSError, subprocess.SubprocessError):
        pass


def still_blocked(dev_id: str) -> bool:
    """Recheck the live permission; a failed read cannot authorize a notification action."""
    try:
        r = ug("list-devices", "-b")
        return r.returncode == 0 and re.search(rf"^{re.escape(dev_id)}: block ", r.stdout, re.M) is not None
    except (OSError, subprocess.SubprocessError):
        return False


def close_input_card(dev_id: str, cards=None) -> None:
    with asking_lock:
        nid = (input_cards if cards is None else cards).pop(dev_id, "")
    if nid.isdigit():
        threading.Thread(target=close_card, args=(nid,), daemon=True).start()


def unplugged(dev_id: str) -> None:
    locked_arrivals.discard(dev_id)
    close_input_card(dev_id)
    close_input_card(dev_id, blocked_cards)
    with asking_lock:
        trim_gone()
        gone[dev_id] = time.monotonic()
        you_blocked.discard(dev_id)
        settings_unblocked(dev_id)
        reask.pop(dev_id, None)
        if dev_id in pending:
            pending_removed.add(dev_id)
        nid = asking.pop(dev_id, "")
    if nid.isdigit():
        threading.Thread(target=close_card, args=(nid,), daemon=True).start()   # the watch keeps reading meanwhile


def notify_wait(dev_id: str, *args) -> str:
    """notify-send that waits for the answer, with the card's id kept in `asking` while it is up."""
    p = subprocess.Popen([*['/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", "Starchaser", "-p", *args], stdout=subprocess.PIPE, text=True)
    nid = (p.stdout.readline() or "").strip()          # -p prints the id as soon as the card is shown
    if nid.isdigit():
        blocked = still_blocked(dev_id)              # approval may have happened before this late id arrived
        with asking_lock:
            trim_gone()
            late = not blocked or dev_id in gone or dev_id in pending_removed
            if not late:
                asking[dev_id] = nid
        if late:
            close_card(nid)
    answer = p.stdout.read().strip()
    p.wait()
    with asking_lock:
        valid = asking.get(dev_id) == nid and dev_id not in gone and dev_id not in pending_removed
        if valid:
            asking.pop(dev_id, None)
    return answer if valid else ""


def ask(dev_id: str, rule: str) -> None:
    time.sleep(0.4)  # Let a dock enumerate its parts before asking one question for that connection.
    try:
        group = next((g for g in status().get("groups", []) if int(dev_id) in g["ids"]), None)
    except (ValueError, OSError, RuntimeError, subprocess.SubprocessError):
        group = None
    if group:
        if int(dev_id) != min(group["ids"]):
            return
        answer = notify_wait(dev_id, "-u", "critical", "-i", "drive-removable-media", "-A", "once=Allow all for now", "-A", "block=Keep blocked", "-A", "help=Ask someone for help", "-w",
                             group["name"] + ": " + str(len(group["ids"])) + " parts. Allow all?",
                             ", ".join(group["parts"]) + "\nAn administrator password is needed. These parts are allowed until unplugged.")
        if answer == "help":
            subprocess.Popen(["starchaser", "settings", "help"], start_new_session=True)
        elif answer == "once":
            result = ug("allow-group", ",".join(map(str, group["ids"])))
            if result.returncode == 0:
                for number in group["ids"]:
                    remember_once(str(number))
            elif result.returncode != 126:
                notify("-u", "critical", "USB dock still blocked", "Check the dock in Settings > Privacy > USB protection.")
        return
    what = label(rule)
    # how long each choice lasts, in the six lines the popup shows: "once" is until it's unplugged (or usbguard
    # restarts, as it does with the computer), "always" is a rule tied to this USB port (allow-device -p), "never" is
    # Always block (Derek 2026-11-07 #29: a device you never want stops asking, without being let in first). The popup's
    # text is 45 letters wide (JetBrains Mono 11 px in a 298 px column): with the keyboard's cover example and advice
    # this fits six lines for a name up to 30 letters, so a longer name is cut short here
    k = kind(rule)
    # one short line each so each fits the 45-letter popup line
    unsure = "\nDidn't plug one in? Keep it blocked." if "keyboard" in k else ""
    short = what if len(what) <= 30 else what[:29].rstrip() + "…"
    storage_device = k in ("storage", "drive", "storage device") or "storage" in k
    body = (f"{short} was plugged in while the screen was locked, so it is blocked until you allow it. Allowing asks for an administrator password."
            if storage_device and dev_id in locked_arrivals else
            f"{short} is blocked until you allow it. Allowing asks for an administrator password.{unsure}")
    answer = notify_wait(dev_id, *same_device(rule), "-u", "critical", "-i", icon(rule), "-A", "once=Open" if storage_device else "once=Allow for now", "-A", "always=Always allow",
                    "-A", "block=Not this time" if storage_device else "block=Keep blocked", "-A", "never=Always block", "-A", "help=Ask someone for help", "-w", short if storage_device else ("A keyboard was plugged in while locked" if dev_id in locked_arrivals and "keyboard" in k else "A USB device was plugged in while locked" if dev_id in locked_arrivals else f"New {k if k.startswith('USB ') else 'USB ' + k}: allow it?"),
                    body)
    if answer == "help":
        subprocess.Popen(["starchaser", "settings", "help"], start_new_session=True)
        return
    if answer == "never" and still_blocked(dev_id):
        with asking_lock:
            valid = dev_id not in gone and dev_id not in pending_removed
            if valid:
                you_blocked.add(dev_id)                 # this answer's own block: no "always blocked" word on top
        if valid:
            if block_device(dev_id, True):
                notify("-i", icon(rule), f"USB {k} always blocked",
                       f"{short} stays blocked every time it's plugged in, until you Unblock it in Settings > Privacy.")
            else:
                with asking_lock:
                    you_blocked.discard(dev_id)
                notify("-u", "critical", "-i", "dialog-error", "USB: not always blocked",
                       f"{short} is blocked until you unplug it. Try Settings > Privacy > USB.")
        return
    if answer in ("once", "always") and still_blocked(dev_id):
        with asking_lock:
            valid = dev_id not in gone and dev_id not in pending_removed
        if valid:
            before = relaxed_now() if answer == "always" else set()
            if storage_device:
                from starchaser_files_common import atomic_json
                marker = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "starchaser-drive-open" / (dev_id + ".json")
                marker.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
                atomic_json(marker, {"serial": field(rule, "serial"), "port": field(rule, "via-port"), "created": time.time()})
            r = ug("allow-device", *(["-p"] if answer == "always" else []), dev_id)
            if r.returncode == 0 and answer == "once":
                remember_once(dev_id)
            if r.returncode == 0 and answer == "always":
                keep_relaxed(before)
            if r.returncode == 126:
                # The password prompt may outlive this attachment or an approval in Settings.
                blocked = still_blocked(dev_id)
                with asking_lock:
                    valid = blocked and dev_id not in gone and dev_id not in pending_removed
                if valid:
                    # Track its lifetime like the question, including IDs delivered after removal.
                    # Transient also withdraws low-urgency history when the device stops being blocked.
                    notify_wait(dev_id, "-w", *same_device(rule), "-h", "boolean:transient:true",
                                "-u", "low", "-i", icon(rule), "USB: still blocked",
                                f"{short} stays blocked. Allow it in Settings > Privacy > USB protection.")
            elif r.returncode != 0:
                notify_wait(dev_id, "-w", "-u", "critical", "-i", "dialog-error",
                            "USB: still blocked",
                            f"{short} couldn't be allowed. Try Settings > Privacy > USB protection.")



def input_card(dev_id: str, *args, cards=None) -> str:
    """notify-send that waits for the answer, with the card's id kept in `input_cards` (or `cards`) while it is up
    ("" until the id comes); "" when it was closed because the device was unplugged or blocked meanwhile."""
    cards = input_cards if cards is None else cards
    with asking_lock:
        cards[dev_id] = ""
    p = subprocess.Popen([*['/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", "Starchaser", "-p", *args], stdout=subprocess.PIPE, text=True)
    nid = (p.stdout.readline() or "").strip()          # -p prints the id as soon as the card is shown
    with asking_lock:
        late = cards.get(dev_id) != ""                  # unplugged or blocked before the id came
        if not late:
            cards[dev_id] = nid
    if late and nid.isdigit():
        close_card(nid)
    answer = p.stdout.read().strip()
    p.wait()
    with asking_lock:
        valid = not late and cards.get(dev_id) == nid
        if valid:
            cards.pop(dev_id, None)
    return answer if valid else ""


def input_notice(dev_id: str, rule: str, seen: set) -> None:
    """The Relaxed level's "new keyboard or mouse" notice, with Block it for one that wasn't plugged in on purpose
    (QA 20261102-2236 003: the notice had no button, and blocking it meant finding Settings and Strict). Blocked
    until it is unplugged; plugged in again, it works and the notice comes back. It stays until OK or Block it
    (-t 0; QA 20261103-0739 003: it faded before a person had read it, taking Block it with it). USB settings opens
    Settings > Privacy at USB protection, where the level is (QA 20261103-1632 001: nothing pointed to it)."""
    answer = input_card(dev_id, *same_device(rule), "-i", "input-keyboard", "-t", "0", "-A", "ok=OK", "-A", "block=Block it",
                        "-A", "always=Always block", "-A", "settings=USB settings", "-w", f"New {kind(rule)} connected",
                        f"{label(rule)}." + (" If you didn't plug in a keyboard just now, press Block it, then unplug it." if "keyboard" in kind(rule) else " You can change this device in USB protection."))
    if answer == "settings":
        usb_settings()
    if answer not in ("block", "always"):
        return
    h = field(rule, "hash")
    if not plugged_in(dev_id, h, "allow"):
        return
    # QA 20261103-0542 002: the block itself is a new decision, which asked "allow it?" right after Block it
    with asking_lock:
        you_blocked.add(dev_id)
    if not block_device(dev_id, answer == "always"):
        with asking_lock:
            you_blocked.discard(dev_id)
        notify("-u", "critical", "-i", "dialog-error", "USB: not blocked",
               f"{label(rule)} could not be blocked. Unplug it.")
        return
    seen.discard(h)
    while True:
        # Undo for a Block it pressed by mistake, and USB settings, which the blocked notice replaced (QA 2026-11-05: getting
        # the keyboard back took Settings > Privacy > USB protection). Kept up like the first notice, until unplugged.
        # It says how long the block lasts (QA 20261106-2144 003: working again on the next plug-in was a surprise);
        # Block it's notice can still make it Always block (Derek 2026-11-07 #29)
        if answer == "always":
            answer = input_card(dev_id, *same_device(rule), "-i", "input-keyboard", "-t", "0", "-A", "undo=Undo",
                                "-A", "settings=USB settings", "-w", f"{kind(rule).capitalize()} always blocked",
                                f"{label(rule)}. Blocked every time it's plugged in, until you Unblock it in "
                                "Settings > Privacy.", cards=blocked_cards)
            always = True
        else:
            answer = input_card(dev_id, *same_device(rule), "-i", "input-keyboard", "-t", "0", "-A", "undo=Undo",
                                "-A", "always=Always block", "-A", "settings=USB settings",
                                "-w", f"{kind(rule).capitalize()} blocked",
                                f"{label(rule)}. Blocked until you unplug it; plug it in again and it works.", cards=blocked_cards)
            always = False
        if answer == "settings":
            usb_settings()
        if answer not in ("undo", "always") or not plugged_in(dev_id, h, "block"):
            return
        if answer == "always":
            if not block_device(dev_id, True):
                notify("-u", "critical", "-i", "dialog-error", "USB: not always blocked",
                       f"{label(rule)} is blocked until you unplug it. Try Settings > Privacy > USB.")
                return
            continue
        if always and not unblock(h):
            notify("-u", "critical", "-i", "dialog-error", "USB: still always blocked",
                   f"{label(rule)} could not be unblocked. Try Settings > Privacy > USB.")
            return
        break
    with asking_lock:
        you_blocked.discard(dev_id)
    if ug("allow-device", dev_id).returncode:
        notify("-u", "critical", "-i", "dialog-error", "USB: still blocked",
               f"{label(rule)} could not be allowed. Try Settings > Privacy > USB.")
        return
    remember_once(dev_id)                       # allowed for this connection, as "Allow for now" is
    seen.add(h)                                 # and not named again as new while it stays plugged in


def unblock(h: str) -> bool:
    """Undo Always block for the device with this hash: remove its block rules (and put back a Relaxed rule the
    block took over)."""
    ok = False
    for _ in range(5):                          # one rule each time block-device -p was used on it
        number = always_blocked().get(h)
        if number is None:
            ok = True
            break
        if ug("remove-rule", str(number)).returncode:
            break
    keep_relaxed(set())
    return ok


def usb_settings() -> None:
    subprocess.Popen(["hyprctl", "dispatch", 'hl.dsp.exec_cmd([[starchaser settings privacy "USB protection"]])'], stdin=subprocess.DEVNULL,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)


def always_blocked_notice(rule: str) -> None:
    if notify(*same_device(rule), "-i", "input-keyboard" if "03:" in " ".join(interfaces(rule)) else icon(rule),
              "-A", "settings=USB settings", f"USB {kind(rule)} blocked",
              f"{label(rule)} is always blocked. To use it again, Unblock it in Settings > Privacy.") == "settings":
        usb_settings()


def plugged_in(dev_id: str, h: str, target: str) -> bool:
    """The same device is still plugged in under that number, allowed or blocked (a number can be reused once it's
    unplugged)."""
    listed = ug("list-devices")
    return not listed.returncode and any(
        field(rest, "hash") == h for rest in re.findall(rf"^{re.escape(dev_id)}: {target} (.*)$", listed.stdout, re.M))


def lines(fd: int):
    """The lines read from a terminal's other end until the program on it exits (EIO), without the \\r it adds."""
    buf = b""
    while True:
        try:
            data = os.read(fd, 65536)
        except OSError:
            data = b""
        if not data:
            if buf:
                yield buf.decode(errors="replace").rstrip("\r")
            return
        buf += data
        *done, buf = buf.split(b"\n")
        for line in done:
            yield line.decode(errors="replace").rstrip("\r")


def watch_events() -> None:
    import ctypes
    import select
    import signal
    parent = os.getppid()
    ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)
    if os.getppid() != parent:
        return
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
    master, slave = pty.openpty()
    child = subprocess.Popen(["usbguard", "watch"], stdin=subprocess.DEVNULL, stdout=slave, stderr=subprocess.DEVNULL)
    os.close(slave)
    try:
        print("changed", flush=True)
        while child.poll() is None:
            if select.select([master], [], [], 30)[0]:
                try:
                    if not os.read(master, 65536):
                        break
                except OSError:
                    break
            print("changed", flush=True)  # slow fallback also notices a protection-level restart
    finally:
        child.terminate()
        try:
            child.wait(timeout=2)
        except subprocess.TimeoutExpired:
            child.kill()
            child.wait()
        os.close(master)


def start_phone_worker() -> None:
    def phones():
        while True:
            try:
                subprocess.run(["starchaser", "files", "tools", "watch-phones"])
            except OSError:
                pass
            time.sleep(5)
    threading.Thread(target=phones, daemon=True).start()


def usb_events(send) -> None:
    while True:
        try:
            read_usb_events(send)
        except (OSError, subprocess.SubprocessError) as error:
            print(f"starchaser usb: couldn't read USB devices: {error}", file=sys.stderr)
        time.sleep(5)


def read_usb_events(send) -> None:
    """Read USBGuard records only. The arrival owner handles all decisions."""
    while True:
        if not shutil.which("usbguard") or subprocess.run(["systemctl", "is-active", "--quiet", "usbguard.service"]).returncode:
            time.sleep(30)
            continue
        master, slave = pty.openpty()
        try:
            child = subprocess.Popen(["usbguard", "watch"], stdin=subprocess.DEVNULL, stdout=slave, stderr=subprocess.DEVNULL)
        except OSError:
            os.close(master)
            raise
        finally:
            os.close(slave)
        rec = {}
        send('usb-connected')
        try:
            for line in lines(master):
                match = re.match(r"\[device\] (\w+): id=(\d+)", line)
                if match:
                    if rec:
                        send('usb', rec)
                    rec = {"kind": match.group(1), "id": match.group(2)}
                elif line.startswith(" ") and "=" in line:
                    key, _, value = line.strip().partition("=")
                    rec[key] = value
                    if key == 'rule_id' or (key == 'device_rule' and rec.get('kind') == 'PresenceChanged'):
                        send('usb', rec)
                        rec = {}
            if rec:
                send('usb', rec)
        finally:
            os.close(master)
            child.terminate()
            try:
                child.wait(timeout=2)
            except subprocess.TimeoutExpired:
                child.kill()
                child.wait()
        time.sleep(5)


def usb_arrival_handler():
    seen_input = set()
    relaxed = set()

    def handle(r):
        if r is None:
            relaxed.clear()
            relaxed.update(relaxed_rule_ids())
            with asking_lock:
                you_blocked.clear()
            settings_unblocked()
            reconcile()
            return
        if r.get("kind") == "PresenceChanged":
            dev = r.get("id", "")
            if r.get("event", "").startswith("Remove"):
                unplugged(dev)
                seen_input.discard(field(r.get("device_rule", ""), "hash"))
            elif r.get("event", "").startswith(("Insert", "Present")):
                present(dev)
            return
        if r.get("kind") != "PolicyApplied":
            return
        rule, dev = r.get("device_rule", ""), r.get("id", "")
        if r.get("target_new") == "block":
            close_input_card(dev)                  # a switch to Strict blocked it: its OK no longer holds
            with asking_lock:
                chosen = dev in you_blocked or settings_blocked(dev)
            if not chosen and field(rule, "hash") and field(rule, "hash") in always_blocked():
                # always blocked: no "allow it?", but a word that it was plugged in and where to undo that
                # USB settings opens the page where Unblock is (QA 20261109-1952 001: the notice had no button)
                threading.Thread(target=always_blocked_notice, args=(rule,), daemon=True).start()
                return
            queue_ask(dev, rule)
            return
        if r.get("target_new") not in ("allow", "reject"):
            return
        unplugged(dev)
        rid = int(r["rule_id"]) if r.get("rule_id", "").isdigit() else None
        if r.get("target_new") == "allow" and rid is not None and rid not in relaxed:
            # keep_relaxed() puts a Relaxed rule back under a new id (after Always allow or Forget): read the ids
            # again, or every new keyboard would come in with no "New keyboard connected · Block it" notice
            relaxed.update(relaxed_rule_ids())
        if r.get("target_new") == "allow" and rid is not None and rid in relaxed:
            h = field(rule, "hash")
            if h and h not in seen_input and "03:" in " ".join(interfaces(rule)):
                seen_input.add(h)
                threading.Thread(target=input_notice, args=(dev, rule, seen_input), daemon=True).start()
    return handle


def start_thunderbolt_worker():
    # One device-question service owns both transports. Thunderbolt consent keeps
    # working when USBGuard is off and never reuses its permissions or block actions.
    import runpy
    thunderbolt = runpy.run_path(str(Path(__file__).resolve().with_name("starchaser-thunderbolt")))
    threading.Thread(target=thunderbolt["watch"], daemon=True).start()


def watch() -> None:
    start_thunderbolt_worker()
    import runpy
    from types import SimpleNamespace
    from starchaser_device_arrivals import ArrivalOwner
    storage = SimpleNamespace(**runpy.run_path(str(Path(__file__).resolve().with_name("starchaser-automount"))))
    start_phone_worker()
    ArrivalOwner(storage, usb_arrival_handler(), reconcile).run(usb_events)


def connected_devices(sysfs: Path = Path("/sys/bus/usb/devices")) -> list:
    """Read-only inventory while USBGuard is stopped; these are USB ports, not USBGuard IDs."""
    devices = []
    for device in sorted(sysfs.iterdir()):
        if not re.fullmatch(r"\d+-\d+(?:\.\d+)*", device.name):
            continue                                           # root controllers and individual interfaces
        try:
            vendor = (device / "idVendor").read_text().strip()
            product_id = (device / "idProduct").read_text().strip()
            product = device / "product"
            name = product.read_text().strip() if product.exists() else ""
            allowed = (device / "authorized").read_text().strip() == "1"
            classes = [(interface / "bInterfaceClass").read_text().strip()
                       for interface in sorted(device.glob(device.name + ":*"))]
        except FileNotFoundError:
            continue                                           # unplugged during the read; next refresh catches up
        description = "with-interface { " + " ".join(c + ":*:*" for c in classes) + " }"
        devices.append({"id": device.name, "state": "allow" if allowed else "block",
                        "name": name or f"USB device {vendor}:{product_id}", "kind": kind(description),
                        "remembered": False, "how": "off" if allowed else "unavailable"})
    return devices


# The policy directory is private; the root helper publishes only this saved choice.
USB_OFF = Path("/var/lib/starchaser/usb-off")


def dock_groups(devices: list) -> list:
    groups = []
    for hub in devices:
        if hub.get("kind") != "USB hub" or not hub.get("port"):
            continue
        prefix = hub["port"] + "."
        parts = [d for d in devices if d.get("port", "").startswith(prefix) and d.get("state") != "allow"]
        if len(parts) > 1:
            groups.append({"name": hub["name"], "ids": [d["id"] for d in parts], "parts": [d["name"] for d in parts]})
    return groups


def question_helper() -> dict:
    try:
        running = subprocess.run(["systemctl", "--user", "is-active", "--quiet", "starchaser-usb.service"], capture_output=True, timeout=5).returncode == 0
    except (OSError, subprocess.SubprocessError):
        running = False
    return {"running": running}


def fix_questions() -> dict:
    result = subprocess.run(["systemctl", "--user", "restart", "starchaser-usb.service", "starchaser-automount.service"], capture_output=True, text=True, timeout=20)
    healthy = question_helper()["running"]
    return {"ok": result.returncode == 0 and healthy, "message": "USB questions are working again." if result.returncode == 0 and healthy else "USB questions still aren't working. Open Help > Hardware for more help."}


def status() -> dict:
    active = shutil.which("usbguard") and subprocess.run(["systemctl", "is-active", "--quiet", "usbguard.service"]).returncode == 0
    if not active:
        return {"level": "off" if USB_OFF.exists() else "unavailable", "devices": connected_devices(), "remembered": [], "blocked": []} if shutil.which("usbguard") else {
            "level": "missing", "devices": [], "remembered": [], "blocked": []}
    rules_read = ug("list-rules")
    devices_read = ug("list-devices")
    if rules_read.returncode or devices_read.returncode:
        raise RuntimeError("Couldn't read USB protection. Try again.")
    rules = rules_read.stdout
    # both rules: with only the hub rule left, keyboards plugged in wait like any device, so this isn't Relaxed
    level = "relaxed" if relaxed_classes(rules) == {"03", "09"} else "strict"
    unknown = []
    for line in rules.splitlines():
        match = re.fullmatch(r"(\d+): (.*)", line)
        if not match:
            continue
        number, rule = match.groups()
        own_default = rule in ("block with-interface one-of { 03:00:* 03:01:01 } if allowed-matches(with-interface one-of { 03:00:* 03:01:01 })",
                               "block with-interface one-of { 03:00:* 03:01:01 }", *RELAXED_OPEN)
        if not own_default and not (field(rule, "hash") and re.search(r"\bid [0-9a-f]{4}:[0-9a-f]{4}\b", rule)):
            unknown.append({"rule": int(number), "text": rule})
    if unknown:
        level = "custom"
    remembered = []
    for m in re.finditer(r"^(\d+): (allow .*)$", rules, re.M):
        r = m.group(2)
        if re.search(r"with-interface all-of \{ (?:0[3689]|ff):", r) and " id " not in r:
            continue                                           # the Relaxed level's own rules
        if re.search(r'name "xHCI Host Controller"|\bid 1d6b:', r):
            continue                                           # the computer's own USB controllers
        remembered.append({"rule": int(m.group(1)), "name": label(r), "kind": kind(r), "hash": field(r, "hash"),
                           "port": field(r, "via-port"), "pluggedIn": False})
    # Always block: a rule with the device's hash and no port, so it blocks the device in any socket
    blocked = [{"rule": number, "name": label(r), "kind": kind(r), "hash": h, "pluggedIn": False}
               for h, number in always_blocked(rules).items()
               for r in re.findall(rf"^{number}: (block .*)$", rules, re.M)]
    by_hash = {}
    for x in remembered:
        if x["hash"]:
            by_hash.setdefault(x["hash"], []).append(x)
    devices = []
    for m in re.finditer(r"^(\d+): (allow|block|reject) (.*)$", devices_read.stdout, re.M):
        if re.search(r"\bid 1d6b:", m.group(3)):
            continue
        h, port = field(m.group(3), "hash"), field(m.group(3), "via-port")
        # a remembered rule matches only on the port it was remembered on (allow-device -p writes via-port): the
        # same device moved to another port isn't covered by it and asks again
        rule = next((x for x in by_hash.get(h, []) if not x["port"] or x["port"] == port), None) if h else None
        if rule:
            rule["pluggedIn"] = True
        block = next((x for x in blocked if x["hash"] == h), None) if h else None
        if block:
            block["pluggedIn"] = True
        # why an allowed device works: a device you allowed always (remembered), a keyboard, mouse or hub the
        # Relaxed level lets in, or allowed this time only (asks again next time it's plugged in)
        classes = {i.split(":")[0] for i in interfaces(m.group(3))}
        how = ("" if m.group(2) != "allow" else "remembered" if rule
               else "relaxed" if level == "relaxed" and classes in ({"03"}, {"09"}) else "once")
        devices.append({"id": int(m.group(1)), "state": m.group(2), "name": label(m.group(3)), "kind": kind(m.group(3)),
                        "hash": h, "port": port, "remembered": bool(rule), "rule": rule["rule"] if rule else None, "how": how,
                        "blockRule": block["rule"] if block else None})
    return {"level": level, "devices": devices, "remembered": remembered, "blocked": blocked, "unknown": unknown, "groups": dock_groups(devices)}


def fail_plain(r, number: str, what: str) -> None:
    """A refused allow/forget in plain words. Only a lookup that confirms the number is gone is called "no longer
    connected"; any other failure keeps its own reason, so a real fault is never mislabeled as a missing device."""
    if r.returncode == 126:
        sys.exit(126)
    detail = (r.stderr or r.stdout or "").strip()
    gone = False
    try:
        st = status()
        if st["level"] in ("off", "missing"):                  # nothing was listed, so absence proves nothing
            raise RuntimeError("USB protection isn't running")
        known = ({d["id"] for d in st["devices"]} if what == "device"
                 else {x["rule"] for x in st["blocked" if what == "blocked rule" else "remembered"]})
        gone = int(number) not in known
    except (OSError, subprocess.SubprocessError, RuntimeError, ValueError, KeyError, TypeError):
        pass
    if gone and what == "device":
        msg = (f"starchaser usb: device {number} is no longer connected or isn't available. "
               "Run 'starchaser usb status' to see the current device numbers.")
    elif gone and what == "blocked rule":
        msg = (f"starchaser usb: there's no always-blocked rule {number}. "
               "Run 'starchaser usb status' to see the current numbers.")
    elif gone:
        msg = (f"starchaser usb: there's no remembered rule {number}. "
               "Run 'starchaser usb status' to see the current numbers.")
    else:
        msg = (f"starchaser usb: USB protection couldn't change {what} {number}. Try again; "
               "if it keeps failing, check that USB protection is running.")
    print(msg, file=sys.stderr)
    if detail and not gone:
        print(f"  (technical detail: {detail})", file=sys.stderr)
    sys.exit(1)


def name_of(number: str, what: str) -> str:
    """The device's or remembered rule's name for a confirmation line; its number when it can't be read."""
    try:
        st = status()
        items = st["devices"] if what == "device" else st["blocked" if what == "blocked rule" else "remembered"]
        key = "id" if what == "device" else "rule"
        return next(x["name"] for x in items if x[key] == int(number))
    except (OSError, subprocess.SubprocessError, RuntimeError, ValueError, KeyError, TypeError, StopIteration):
        return number


def main(argv: list) -> None:
    global WATCHING
    cmd = argv[0] if argv else "status"
    if any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__)                                  # help after a command: the help, nothing changed
        sys.exit(0)
    commands = {
        "watch": ("watch", (), ()),
        "status": ("status", (), ()),
        "ask": ("ask <device-number>", ("device number",), ()),
        "allow": ("allow <device-number> [--always]", ("device number",), ()),
        "forget": ("forget <rule-number>", ("rule number",), ()),
        "block": ("block <device-number> [--always]", ("device number",), ()),
        "unblock": ("unblock <rule-number>", ("rule number",), ()),
    }
    if cmd == "helper-status" and len(argv) == 1:
        print(json.dumps(question_helper())); return
    if cmd == "fix-questions" and len(argv) == 1:
        result = fix_questions(); print(json.dumps(result)); sys.exit(0 if result["ok"] else 1)
    if cmd in ("watch", "status") and len(argv) > 1:
        sys.exit(command_usage_error("starchaser usb", argv, commands))
    if cmd == "watch-events" and len(argv) == 1:
        watch_events()
    elif cmd == "watch":
        WATCHING = True
        watch()
    elif cmd == "allow-group" and len(argv) == 2 and re.fullmatch(r"[0-9]+(?:,[0-9]+){1,31}", argv[1]):
        result = ug("allow-group", argv[1])
        if result.returncode == 126:
            sys.exit(126)
        if result.returncode:
            sys.exit("The dock parts could not be allowed. Check USB protection again.")
        for number in argv[1].split(","):
            remember_once(number)
        print(json.dumps({"ok": True}))
    elif cmd == "ask" and len(argv) == 2 and argv[1].isdigit():
        if Path("/run/starchaser/usb-locked").exists():
            return
        result = ug('list-devices')
        match = re.search(r'^' + re.escape(argv[1]) + r': (block|reject) (.*)$', result.stdout, re.M) if result.returncode == 0 else None
        if match:
            ask(argv[1], match.group(2))
    elif cmd == "status":
        try:
            print(json.dumps(status()))
        except (OSError, subprocess.SubprocessError, RuntimeError):
            print("Couldn't read USB protection. Try again.", file=sys.stderr)
            sys.exit(1)
    # only "allow N" or "allow N --always": a misspelled "--alway" must not allow the device for this time only
    elif cmd == "allow" and len(argv) in (2, 3) and argv[1].isdigit() and argv[2:] in ([], ["--always"]):
        name = name_of(argv[1], "device")
        before = relaxed_now() if "--always" in argv else set()
        r = ug("allow-device", *(["-p"] if "--always" in argv else []), argv[1])
        if r.returncode:
            fail_plain(r, argv[1], "device")
        if "--always" not in argv:
            remember_once(argv[1])
        else:
            keep_relaxed(before)
        if sys.stdout.isatty():   # Settings and scripts read the values back and see no change; a terminal is told
            print(f"Allowed '{name}' now and from now on." if "--always" in argv else f"Allowed '{name}' for now.")
    elif cmd == "block" and len(argv) in (2, 3) and argv[1].isdigit() and argv[2:] in ([], ["--always"]):
        name = name_of(argv[1], "device")
        always = "--always" in argv
        BLOCKED_DIR.mkdir(parents=True, exist_ok=True)     # before the block, so the watch sees it when it's told
        (BLOCKED_DIR / argv[1]).touch()
        before = relaxed_now() if always else set()
        r = ug("block-device", *(["-p"] if always else []), argv[1])
        if r.returncode:
            settings_unblocked(argv[1])
            fail_plain(r, argv[1], "device")
        if always:
            keep_relaxed(before)
        remember_once(argv[1], remove=True)
        if sys.stdout.isatty():
            print(f"Blocked '{name}' every time it's plugged in." if always else f"Blocked '{name}' until it's unplugged.")
    elif cmd == "unblock" and len(argv) == 2 and argv[1].isdigit():
        name = name_of(argv[1], "blocked rule")
        # only an Always block rule: Unblock never removes a rule that lets a device in
        if int(argv[1]) not in always_blocked().values():
            fail_plain(subprocess.CompletedProcess([], 1, "", ""), argv[1], "blocked rule")
        r = ug("remove-rule", argv[1])
        if r.returncode:
            fail_plain(r, argv[1], "blocked rule")
        keep_relaxed(set())
        if sys.stdout.isatty():
            print(f"'{name}' is no longer always blocked. Plugged in again, it's treated as a new device.")
    elif cmd == "forget" and len(argv) == 2 and argv[1].isdigit():
        name = name_of(argv[1], "rule")
        r = ug("remove-rule", argv[1])
        if r.returncode:
            fail_plain(r, argv[1], "remembered rule")
        keep_relaxed(set())
        if sys.stdout.isatty():   # Settings and scripts read the values back and see no change; a terminal is told
            print(f"'{name}' will wait for you next time it's plugged in.")
    else:
        message = None
        if cmd in ("allow", "forget", "block", "unblock"):
            number = "rule number" if cmd in ("forget", "unblock") else "device number"
            if len(argv) == 1 or (cmd in ("allow", "block") and argv[1:] == ["--always"]):
                message = f"missing {number}"
            elif argv[1].startswith("-"):
                message = f"unexpected option {argv[1]!r}"
            elif not argv[1].isdigit():
                message = f"invalid {number} {argv[1]!r}"
            else:
                extra = argv[3] if cmd in ("allow", "block") and argv[2] == "--always" else argv[2]
                message = f"unexpected {'option' if extra.startswith('-') else 'argument'} {extra!r}"
            message += f". Run 'starchaser usb status' to see the current {number}s."
        sys.exit(command_usage_error("starchaser usb", argv, commands, message))



if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]):      # usage on request is not an error
        print(__doc__)
        sys.exit(0)
    main(sys.argv[1:])
