#!/usr/bin/env -S python3 -X utf8
# summary: Find, install, remove, and inspect apps.
"""starchaser software: the engine behind Settings > Software.

Installing system apps asks for your password (once for a batch: 15 minutes after the last install or update, in
that login session, and once for a whole install queue, however long it takes); Flathub apps install just for you,
with no password.

    starchaser software details <source> <name>   storage, permissions, startup and update capabilities (JSON)
    starchaser software app-action <source> <name> <action> [args]   startup on|off, permission KEY on|off,
                                             reset-permissions, hold, unhold, update, repair, previous-version, go-back COMMIT, delete-data confirm
    starchaser software answer <words>       a familiar-app answer card, or null (JSON)
    starchaser software screenshots <Flathub id> <title>   up to three screenshots with descriptions (JSON)
    starchaser software inventory            portable app identities for Bring my apps (JSON)
    starchaser software import-plan          read an inventory on stdin and list missing apps (JSON)
    starchaser software import-add           read the selected inventory on stdin and add it to the install queue
    starchaser software storage              known storage and safe cleanup information (JSON)
    starchaser software catalog              the curated catalog with what's installed and where each app can
                                             come from on this computer (JSON; "aur": whether the Community recipes source answered,
                                             and an app's "aurUnknown": its Community recipes source couldn't be checked)
    starchaser software app <catalog id>     the same information for one app, without waiting for other apps' sources
    starchaser software search <words>       the system's app library, Community recipes and Flathub (JSON; "aurError"
                                             says why Community recipes weren't searched)
    starchaser software plan repo|aur <pkg>  what installing it would take, against fresh app lists (the system's own
                                             lists are untouched): {"install", "upgrade", "core",
                                             "missing", "download"}; "core" non-empty = it needs a full update first
    starchaser software plan flatpak <app id>   what a Flathub install downloads, its shared runtime included when this
                                             computer doesn't have it yet, and what the app may access (JSON; read
                                             from Flathub's API, so nothing is set up or changed here)
    starchaser software plan-ready           refresh those app lists now if they're over 10 minutes old, so a plan asked
                                             for next doesn't wait for it ({"ok": true})
    starchaser software aur-info <pkg>       maintainer, votes, last update, out-of-date flag (JSON)
    starchaser software installed            what you installed yourself: apps, Community recipes, Flatpak (JSON)
    starchaser software run [--update-first] [--clear-stale-lock] install|remove|repair <source> <name> [...]
                                             do it; progress as "@@{json}" lines like the updater.
                                             repair (official apps only) installs it again over itself.
                                             Flathub installs accept "cancel" on stdin once cancelable is true.
                                             --update-first: install the waiting system updates, then this official app
                                             --clear-stale-lock: first clear a package-manager lock an unfinished
                                             install left behind (one password prompt for both)
    starchaser software last-run [update|software]   the last install, removal or update run as root, for a page
                                             opened after it started: {"record": {...}, "key": str, "alive": bool,
                                             "unseen": bool, "log": [last lines]} (record: see updater.py; key: which
                                             run; unseen: no page has shown its result yet)
    starchaser software last-run-seen [update|software [KEY]]   mark that kind's current record (or run KEY) as shown
    starchaser software firewall-draft <firewall app id> <app name> [<asked from>]
                                             draft "allow it on home networks" for the Firewall page to review
                                             (credited there to <asked from>, Software when not given)
                                             ({"exists": true} when a rule already allows it)
    starchaser software open <desktop id>    start an installed app in front of Settings (floated and centered)
    starchaser software website <url>        open a recipe or app website, offering a browser when none is installed
    starchaser software setup <source> <name>   start an installed app's background service and open its setup page
    starchaser software windows <source> <name>   how many of an installed app's windows are open: {"open": n}
    starchaser software offer [--remind] <catalog id> <why>   "Would you like to install …?": a notification with an Install
                                             button that opens the app's sheet; at most once a day per app,
                                             and never for one that's already installed. --remind: for a key
                                             someone pressed: show the same card again even if today's was
                                             shown (unless that card is still up), so pressing it isn't silent
    starchaser software foreign <file>       a downloaded installer made for another system (.deb, .rpm, .exe, .dmg
                                             and the like; Files opens them with this): say it can't install here
                                             and offer to search Software for the app by the file's name. An
                                             AppImage (a Linux app from a website) also offers Run it anyway, and
                                             once it shows a window, Add it to my apps (see appimage below)
    starchaser software run-watch <start time>   (run starts it) once that install or removal ends, say how it
                                             went in a notification if no page showed it (Settings was closed)
    starchaser software queue                the install queue: apps picked while another one installs, installed one
                                             after another (JSON: {"items": [{"id", "source", "name", "title",
                                             "state": waiting|installing|installed|failed, "result", ...}],
                                             "waitNote": why the next one hasn't started})
    starchaser software queue add <source> <name> "<title>" [<firewall app id>]   add an app to it (its helper,
                                             queue-run, starts if needed and keeps going when Settings closes)
    starchaser software queue remove|retry <id>   take a waiting app off it; put a failed one back in line
    starchaser software queue clear|seen     drop the finished rows; mark the end as shown (no notification)
    starchaser software withdraw <catalog id>   take back an offer that is still on screen (Game mode turned off:
                                             its "Steam isn't installed" offer goes, and with it the bell's count)
    starchaser software icons                fetch Flathub's icon for catalog apps that have a Flatpak (cached in
                                             ~/.cache/starchaser/software/icons; the page uses it when the app
                                             isn't installed and the icon theme has nothing)
    starchaser software verify               check every catalog entry against this computer's software sources,
                                             the official repos, Community recipes and Flathub (for catalog editors)
                                             exit 3 if online source checks are incomplete; 0 if all checks finished

Where an app comes from (the <source> above): repo (the system's own app library), aur (apps the community
packages; built on this computer), flatpak (an app from Flathub, named by its Flathub id), vendor (the maker's own
installer, named by its catalog recipe: run as you, into your home folder, and the app updates itself; installing
it removes an older packaged copy once the new one works), appimage (an app from a website the person added to their
apps after Run it anyway, named by its launcher id, appimage-<id>: the file in ~/Applications, its launcher in
~/.local/share/applications and its icon in ~/.local/share/icons; Remove only, as you, and only those three files).
"""
# Root work goes through `pkexec starchaser-admin-software software-run` (or starchaser-admin on older system tools). "repo" means the pacman repos: Arch's own
# core/extra/multilib are "official"; any other repo this computer has is shown as another repo, not part of
# Starchaser. Plans use checkupdates' private copy of the package lists, so the system's are untouched.
import configparser
import difflib
import html
import json
import math
import os
import re
import select
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import command_usage_error, safe_streams, takes_nothing_after, usage_error
from starchaser_personal_apps import checked_file as personal_app_file
from starchaser_personal_apps import list_apps as personal_apps
from starchaser_personal_apps import remove as remove_personal_app

safe_streams()

# Domain modules share command configuration through an explicit context. Keep this
# entry point for CLI callers, detached workers and existing integrations.
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "software_context.py").is_file():
        sys.path.insert(0, str(_lib))
        break
from software_context import SoftwareContext
import software_catalog
import software_inventory
import software_execution
import software_planning
import software_websites
import software_queue


HOME = Path.home()
# Personal entries merge with the checkout catalog, or the installed copy. This script runs from the
# repo (~/.local/bin links into it), so the repo's catalog is the one written for this code; the root-owned copy is
# frozen at setup time and only serves a package install that has no checkout.
CATALOG = [HOME / ".config/starchaser/software/catalog.json", Path(__file__).resolve().parent.parent / "config/software/catalog.json",
           Path("/usr/share/starchaser/software/catalog.json")]
FIREWALL_APPS = [Path("/usr/local/share/starchaser/firewall-apps.json"), Path(__file__).resolve().parent.parent / "config/firewall/apps.json"]
# a package name; never one that starts with "-" or "." (root pacman would read "-c" or "--noconfirm" as options)
NAME = re.compile(r"[a-z0-9@_+][a-z0-9@._+-]{0,99}")
FLATPAK_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+){2,}")
UA = {"User-Agent": "starchaser-software/1"}
BACKUP_BROWSER = "ungoogled-chromium"       # offered when Brave Origin can't be installed right now (from Flathub)
ICONS = HOME / ".cache/starchaser/software/icons"


def sh(*cmd, timeout=60) -> str:
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
                              env={**os.environ, "LANG": "C.UTF-8"}).stdout
    except (OSError, subprocess.TimeoutExpired):
        return ""


def get_json(url, data=None, timeout=15):
    req = urllib.request.Request(url, data=json.dumps(data).encode() if data is not None else None,
                                 headers={**UA, **({"Content-Type": "application/json"} if data is not None else {})})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)


def read_catalog(path):
    return software_catalog.read_catalog(SoftwareContext(globals()), path)


def shipped_catalog():
    return software_catalog.shipped_catalog(SoftwareContext(globals()))


def load_catalog() -> dict:
    return software_catalog.load_catalog(SoftwareContext(globals()))


def unsynced_repos() -> list:
    return software_catalog.unsynced_repos(SoftwareContext(globals()))


def repo_index() -> dict:
    return software_catalog.repo_index(SoftwareContext(globals()))


def foreign() -> set:
    return software_catalog.foreign(SoftwareContext(globals()))


def installed_pkgs() -> dict:
    return software_catalog.installed_pkgs(SoftwareContext(globals()))


def flatpaks() -> dict:
    return software_catalog.flatpaks(SoftwareContext(globals()))


# A maker's own installer (the catalog's "vendors"; decided 2026-11-07 #32): its script is fetched over HTTPS to a
# private temp file and run with bash as the person, never as root, and the app lands in their home folder and updates
# itself, so Updates never sees it. What a recipe names as its files (and Remove deletes) is kept to ~/.local/bin and
# ~/.local/share entries: a damaged or edited catalog can't point Remove at anything else in the home folder.
VENDOR_FILE = re.compile(r"\.local/(bin|share)/[A-Za-z0-9_+-][A-Za-z0-9._+-]{0,99}")
VENDOR_SCRIPT_MAX = 1 << 20     # an install script is a few KB; anything this big is not one


def vendor_recipe(name: str, cat=None):
    return software_catalog.vendor_recipe(SoftwareContext(globals()), name, cat)


def vendor_version(r: dict):
    return software_catalog.vendor_version(SoftwareContext(globals()), r)


def vendor_replaced(r: dict, inst: dict, fm: set) -> list:
    return software_catalog.vendor_replaced(SoftwareContext(globals()), r, inst, fm)


AUR_CACHE = HOME / ".cache/starchaser/software/aur-info.json"
AUR_KEEP = 86400            # a remembered answer stands in for one the AUR didn't give for a day
AUR_FRESH = 3 * 3600        # ... and one this recent is used as it is, without asking again
AUR_COOL = 3600             # after "too many requests" or an outage, ask again no sooner than this at most (seconds)
AUR_COOL_FIRST = 120        # ... and the first time, this


def aur_down(e) -> bool:
    return software_catalog.aur_down(SoftwareContext(globals()), e)


def aur_cool(c: dict, e, now: float) -> None:
    return software_catalog.aur_cool(SoftwareContext(globals()), c, e, now)


def aur_cache() -> dict:
    return software_catalog.aur_cache(SoftwareContext(globals()))


def aur_cache_save(c: dict, seen_cool: float = 0) -> None:
    return software_catalog.aur_cache_save(SoftwareContext(globals()), c, seen_cool)


def aur_lookup(names) -> tuple:
    return software_catalog.aur_lookup(SoftwareContext(globals()), names)


def aur_info(names) -> dict:
    return software_catalog.aur_info(SoftwareContext(globals()), names)


def aur_summary(x: dict) -> dict:
    return software_catalog.aur_summary(SoftwareContext(globals()), x)


def firewall_app_ids() -> set:
    return software_catalog.firewall_app_ids(SoftwareContext(globals()))


# --------------------------------------------------------------------------- catalog
ICON_THEMES = ["Papirus", "hicolor", "AdwaitaLegacy", "Adwaita"]
# where icon themes live: the system, this user, and the icons Flatpak apps export
ICON_BASES = [Path("/usr/share/icons"), HOME / ".local/share/icons", HOME / ".local/share/flatpak/exports/share/icons",
              Path("/var/lib/flatpak/exports/share/icons")]
ICON_SIZES = ["64x64", "scalable", "48x48", "128x128", "256x256", "32x32"]


def themed_icon(name: str) -> str:
    return software_catalog.themed_icon(SoftwareContext(globals()), name)


def catalog_icon(name, flatpak_id):
    return software_catalog.catalog_icon(SoftwareContext(globals()), name, flatpak_id)


def cmd_catalog(app_id=None):
    return software_catalog.cmd_catalog(SoftwareContext(globals()), app_id)


def cmd_icons():
    return software_catalog.cmd_icons(SoftwareContext(globals()))


# --------------------------------------------------------------------------- search
# Arch's AppStream data (archlinux-appstream-data) says which packages are apps a person launches and what they're
# called. It only ranks: a package without an entry (a library, or a terminal app like helix) is still listed.
APPSTREAM = [Path("/usr/share/swcatalog/xml"), Path("/usr/share/app-info/xmls")]
APPSTREAM_CACHE = HOME / ".cache/starchaser/software/appstream.json"
APP_TYPES = {"desktop-application", "desktop", "console-application"}
# names that are almost never what someone searching for an app wants; they sort after the rest, never disappear
LIBISH = re.compile(r"^(lib(?!re)|python-|python2-|perl-|ruby-|haskell-|rust-|go-|r-|nodejs-|ocaml-|lua\d*-|java-|"
                    r"php-|texlive-|ghc-|ttf-|otf-|fonts?-)|-(docs?|devel|headers|bindings|data|common|libs?)$")   # lib(?!re): LibreOffice
# an app whose description says it is made for X11 ("Lightweight color picker for X11"): on this Wayland desktop it
# can't do its job (xcolor picks no colors here), so it folds with the tools instead of leading the apps (QA 2026-11-06)
X11_ONLY = re.compile(r"\b(?:for|on|under)\s+(?:the\s+)?(?:X11|Xorg|X\.Org|X Window(?:s| System)?)\b", re.I)


def x11_only(desc: str) -> bool:
    return software_catalog.x11_only(SoftwareContext(globals()), desc)


def appstream_data() -> tuple:
    return software_catalog.appstream_data(SoftwareContext(globals()))


APPSTREAM_ICONS = [Path("/usr/share/swcatalog/icons"), Path("/usr/share/app-info/icons")]


def appstream_icon(ic: dict) -> str:
    return software_catalog.appstream_icon(SoftwareContext(globals()), ic)


def add_icons(hits):
    return software_catalog.add_icons(SoftwareContext(globals()), hits)


def search_repo(q):
    return software_catalog.search_repo(SoftwareContext(globals()), q)


def word_match(x: dict, words: list) -> bool:
    return software_catalog.word_match(SoftwareContext(globals()), x, words)


def whole_word(x: dict, words: list) -> bool:
    return software_catalog.whole_word(SoftwareContext(globals()), x, words)


def rank_repo(hits, q):
    return software_catalog.rank_repo(SoftwareContext(globals()), hits, q)


def search_aur(q):
    return software_catalog.search_aur(SoftwareContext(globals()), q)


# An app title naming this desktop, including Flathub's "Color Picker for COSMIC™".
OTHER_TITLE = re.compile(r"cosmic\b", re.I)


PURPOSE_SUMMARIES = {
    "galculator": "Calculate with basic and scientific functions",
    "speedcrunch": "Type calculations and review your calculation history",
    "shotcut": "Edit videos",
    "dconf-editor": "Change advanced application settings",
    "gtranslator": "Edit software translations",
    "capitaine-cursors": "Smooth black and white pointer styles",
}
# Use app listings for nearby video, settings and translation editors; leave other package copy alone.
SUMMARY_NEIGHBORS = {"kdenlive", "openshot", "pitivi", "olive", "poedit", "lokalize", "dconf"}
TECHNICAL_SUMMARY = re.compile(r"\b(?:qt|gtk|gsettings|gettext|cross-platform|po file)\b", re.I)


def purpose_summary(name: str, upstream: str, summary: str) -> str:
    return software_catalog.purpose_summary(SoftwareContext(globals()), name, upstream, summary)


# A package named for another desktop (gnome-calculator, xfce4-calculator-plugin) with no app listing to give it a
# plain name: it's listed last, under "Show N more made for other desktops", folded until asked for. Never dropped: some of
# these are ordinary apps that work here too, and the AppStream name (when there is one) lifts them out of the group.
OTHER_DESKTOP = re.compile(r"^(gnome|xfce4?|pantheon|deepin|plasma|kde|cinnamon|mate|budgie|lxqt|lxde|elementary|cosmic|kio|kf[56]|k[a-z]+5?)-", re.I)


ADDON_WORD = re.compile(r"(?:^|[-_\s])(dolphin|plasma|kde)(?=$|[-_\s])", re.I)


def addon_title(name: str, title: str = "") -> str:
    return software_catalog.addon_title(SoftwareContext(globals()), name, title)


def other_desktop(h: dict) -> bool:
    return software_catalog.other_desktop(SoftwareContext(globals()), h)


def spelled_alike(words, h) -> bool:
    return software_catalog.spelled_alike(SoftwareContext(globals()), words, h)


def search_flathub(q):
    return software_catalog.search_flathub(SoftwareContext(globals()), q)


# official packages listed for one search. Ranking never drops anything below this; a search with more hits than
# this (one or two letters) says how many more there are ("repoMore"), so the page can ask for another word
REPO_MAX = 400


def cmd_search(q):
    return software_catalog.cmd_search(SoftwareContext(globals()), q)


# What must never be removed lives in one module that the root helper reads too (it checks a removal's whole plan,
# dependencies included). The checkout's copy first, like the catalog: it's the one written for this code.
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "keep.py").is_file():
        sys.path.insert(0, str(_lib))
        break
from keep import ADDONS, COMPANIONS, keeps_starchaser_running, starchaser_own, system_piece
from software_text import OTHER_NAMES, plain


def desktop_entry(path: Path) -> dict:
    return software_inventory.desktop_entry(SoftwareContext(globals()), path)


def package_description(name: str) -> str:
    return software_inventory.package_description(SoftwareContext(globals()), name)


# The familiar names already used in the menu. Keep the product name in the subtitle and search aliases.
INSTALLED_TITLES = {"kalk": "Kalk", "org.kde.kalk": "Kalk",
                    "aisleriot": "Solitaire", "org.gnome.Aisleriot": "Solitaire",
                    "kshisen": "KShisen", "org.kde.kshisen": "KShisen",
                    "mousepad": "Text editor (Mousepad)", "lite-xl": "Code editor (Lite XL)", "mission-center": "Task manager (Mission Center)",
                    "moonlight-qt": "Game streaming", "yazi": "Files (in the terminal)",
                    "loupe": "Image viewer (Loupe)", "papers": "Document viewer (Papers)", "mpv": "Video player (mpv)",
                    "flea": "Files", "thunar": "Thunar", "kitty": "Terminal", "fastfetch": "System information"}


def needed_by_starchaser(names):
    return software_inventory.needed_by_starchaser(SoftwareContext(globals()), names)


def cmd_installed(snapshot=False, local_only=False):
    return software_inventory.cmd_installed(SoftwareContext(globals()), snapshot, local_only)


def installed_apps(local_only=False):
    return software_inventory.installed_apps(SoftwareContext(globals()), local_only)


# --------------------------------------------------------------------------- doing it
def emit(**ev):
    return software_execution.emit(SoftwareContext(globals()), **ev)


# flatpak's terminal codes (bold, its progress bar's color, the taskbar-progress and cursor-position escapes)
ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")


def flatpak_output(cmd):
    return software_execution.flatpak_output(SoftwareContext(globals()), cmd)


def cancel_flatpak(p, canceled, fd):
    return software_execution.cancel_flatpak(SoftwareContext(globals()), p, canceled, fd)


def relay_cancel(fd, flag, stopped=None):
    return software_execution.relay_cancel(SoftwareContext(globals()), fd, flag, stopped)


def run_root_software(req, flag=None):
    return software_execution.run_root_software(SoftwareContext(globals()), req, flag)


FLATPAK_NETWORK = re.compile(r"could not resolve host|unable to load summary|error contacting|timed out|"
                             r"connection (?:refused|reset)|network is unreachable|temporary failure in name resolution|"
                             r"curl: \(\d+\)|while fetching https?://", re.I)
flatpak_lines = []                  # the last raw lines flatpak printed, to tell "no internet" from other failures


def flatpak_install_failure(ids, lines):
    return software_execution.flatpak_install_failure(SoftwareContext(globals()), ids, lines)


def run_flatpak(action, ids):
    return software_execution.run_flatpak(SoftwareContext(globals()), action, ids)


def drop_partial_downloads():
    return software_execution.drop_partial_downloads(SoftwareContext(globals()))


def flatpak_step(line: str, ids: list) -> str:
    return software_execution.flatpak_step(SoftwareContext(globals()), line, ids)


# pacman's lock left by a crash or power cut ("stale") vs one in use: the rule lives in updater.py, which the root
# helper uses right before it clears a stale lock (one copy). Without it (an older install), never "stale".
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "updater.py").is_file():
        sys.path.insert(0, str(_lib))
        break
try:
    from updater import pacman_lock_state
except ImportError:
    def pacman_lock_state() -> str:
        return "busy" if Path("/var/lib/pacman/db.lck").exists() else ""
try:
    from updater import run_busy
except ImportError:
    def run_busy() -> bool:
        return False

BUSY = "Another install or update is running. Wait for it to finish, then try again."


def locked_checkupdates(db: Path, fresh=None, timeout=180):
    return software_execution.locked_checkupdates(SoftwareContext(globals()), db, fresh, timeout)


def prepare_player(source, names) -> None:
    return software_execution.prepare_player(SoftwareContext(globals()), source, names)


def prepare_browser(source, names) -> None:
    return software_execution.prepare_browser(SoftwareContext(globals()), source, names)


def cmd_run(action, source, names, clear_stale=False, replace=(), remove_plan=None, delete_data=False, update_first=False):
    return software_execution.cmd_run(SoftwareContext(globals()), action, source, names, clear_stale, replace, remove_plan, delete_data, update_first)


def run_vendor(action: str, name: str) -> bool:
    return software_execution.run_vendor(SoftwareContext(globals()), action, name)


def vendor_install(r: dict, maker: str, title: str) -> bool:
    return software_execution.vendor_install(SoftwareContext(globals()), r, maker, title)


def vendor_remove(r: dict, title: str) -> bool:
    return software_execution.vendor_remove(SoftwareContext(globals()), r, title)


def remove_replaced(source: str, names: list) -> bool:
    return software_execution.remove_replaced(SoftwareContext(globals()), source, names)


def account_sync() -> None:
    return software_execution.account_sync(SoftwareContext(globals()))


def open_after_browser(names) -> None:
    return software_execution.open_after_browser(SoftwareContext(globals()), names)


def app_windows(source: str, name: str) -> list:
    return software_execution.app_windows(SoftwareContext(globals()), source, name)


def window_program(client: dict) -> str:
    return software_execution.window_program(SoftwareContext(globals()), client)


def authorize_first(action="", source="", names=()) -> str:
    return software_execution.authorize_first(SoftwareContext(globals()), action, source, names)


def keep_grant() -> None:
    return software_execution.keep_grant(SoftwareContext(globals()))


def close_app_windows(source: str, names) -> bool:
    return software_execution.close_app_windows(SoftwareContext(globals()), source, names)


# Recovery's app names (bin/starchaser-recovery NAME_CACHE): {package: the name its menu entry shows}
APP_NAMES = Path(os.environ.get("XDG_CACHE_HOME") or HOME / ".cache") / "starchaser" / "app-names.json"


def remember_app_names(names) -> None:
    return software_execution.remember_app_names(SoftwareContext(globals()), names)


def stop_setup_services(names) -> None:
    return software_execution.stop_setup_services(SoftwareContext(globals()), names)


def software_root_helper() -> str:
    return software_execution.software_root_helper(SoftwareContext(globals()))


def root_helper() -> str:
    return software_execution.root_helper(SoftwareContext(globals()))


def pkexec_refused(rc: int, err: str) -> str:
    return software_execution.pkexec_refused(SoftwareContext(globals()), rc, err)


def auth_message(auth: str, err: str) -> str:
    return software_execution.auth_message(SoftwareContext(globals()), auth, err)


def plan_db() -> Path:
    return software_planning.plan_db(SoftwareContext(globals()))


def plan_db_fresh(db: Path) -> bool:
    return software_planning.plan_db_fresh(SoftwareContext(globals()), db)



def cmd_remove_plan(source, name):
    return software_planning.cmd_remove_plan(SoftwareContext(globals()), source, name)

def cmd_plan_ready():
    return software_planning.cmd_plan_ready(SoftwareContext(globals()))


def cmd_plan(source, name):
    return software_planning.cmd_plan(SoftwareContext(globals()), source, name)


def flatpak_access(perms: dict) -> list:
    return software_planning.flatpak_access(SoftwareContext(globals()), perms)


def flathub_publisher(app_id) -> dict:
    return software_planning.flathub_publisher(SoftwareContext(globals()), app_id)


def flatpak_transaction_sizes(app_id):
    return software_planning.flatpak_transaction_sizes(SoftwareContext(globals()), app_id)


def cmd_plan_flatpak(app_id):
    return software_planning.cmd_plan_flatpak(SoftwareContext(globals()), app_id)


def canonical_basic(r: dict, fid: str) -> bool:
    # Same shape as Firewall's Simple switch. Rules refined on the Rules page keep their own limits.
    zones = set(r.get("zones") or [])
    return (r.get("managed") == "basic" and r.get("app") == fid and r.get("dir") == "in"
            and r.get("action") == "allow" and r.get("peers") == ["any"] and r.get("user") == "any"
            and not any(r.get(k) for k in ("iface", "rate", "sport", "icmp")) and r.get("state") != "all"
            and (zones == {"any"} or "trusted" in zones and zones <= {"trusted", "tailscale", "vpn"})
            and (r.get("service") == "app-default" or fid == "sunshine" and r.get("service") == ["starchaser-remote-desktop"]))


def cmd_firewall_draft(fid, name, by="Software"):
    import time
    if fid not in firewall_app_ids():
        sys.exit("unknown firewall app")
    # never a draft built on a failed read (sh() hides the exit status): Settings adopts the draft, and applying one
    # made from nothing would replace every rule and switch the firewall off. Read the same way as bin/starchaser-ask.
    policy = None
    try:
        r = subprocess.run(["starchaser", "firewall", "state"], capture_output=True, text=True, timeout=60,
                           env={**os.environ, "LANG": "C.UTF-8"})
        st = json.loads(r.stdout) if r.returncode == 0 else {}
        if isinstance(st, dict) and not st.get("policyUnreadable"):
            policy = st.get("policy")
    except (OSError, subprocess.TimeoutExpired, ValueError):
        pass
    if not isinstance(policy, dict) or not isinstance(policy.get("rules", []), list):
        print(json.dumps({"exists": False, "error": "Couldn't read your firewall settings, so nothing was changed. "
                                                    "Try again in a moment."}))
        sys.exit(1)
    rules = policy.get("rules") or []
    basic = next((r for r in rules if canonical_basic(r, fid)), None)
    if basic is not None and basic.get("enabled", True):
        print(json.dumps({"exists": True}))
        return
    if basic is None and any(r.get("app") == fid and r.get("dir") == "in" and r.get("action") == "allow" and r.get("enabled", True) for r in rules):
        print(json.dumps({"exists": True}))
        return
    rid = "r-sw-" + re.sub(r"[^a-z0-9]", "", fid)[:20]
    title = re.sub(r"[^\w .()-]", "", f"Allow {name} on home networks")[:80]
    if basic is not None:
        basic["enabled"] = True
    else:
        policy["rules"] = [r for r in rules if r.get("id") != rid] + [
            {"id": rid, "name": title, "enabled": True, "dir": "in", "action": "allow", "zones": ["trusted", "tailscale"],
             "peers": ["any"], "user": "any", "app": fid, "service": "app-default", "log": False}]
    d = HOME / ".cache/starchaser/firewall-draft.json"
    d.parent.mkdir(parents=True, exist_ok=True)
    d.write_text(json.dumps({"time": int(time.time()), "policy": policy, "why": title,
                             "by": re.sub(r"[^\w .-]", "", by)[:40] or "Software"}))
    print(json.dumps({"exists": False, "draft": str(d)}))


# --------------------------------------------------------------------------- verify (for catalog editors)
def cmd_verify():
    cat = load_catalog()
    idx = repo_index()
    aur, aur_err, _, aur_unknown = aur_lookup([n for a in cat["apps"] for s, n in a["sources"] if s in ("aur", "repo")])
    if aur_err:
        print(f"Community recipes didn't answer ({aur_err}): its sources show '?' where nothing was remembered.", file=sys.stderr, flush=True)

    def arch(n):
        import ssl
        import time
        for wait in (0, 2, 5):                                     # archlinux.org rate-limits bursts
            time.sleep(wait)
            try:
                return bool(get_json(f"https://archlinux.org/packages/search/json/?name={urllib.parse.quote(n)}")["results"]), ""
            except Exception as e:
                reason = str(e) or type(e).__name__
                if isinstance(getattr(e, "reason", e), ssl.SSLError):
                    reason = "The official app source could not make a secure connection. Try again later.\n  Technical details: " + reason
        return None, reason

    def flathub(i):
        try:
            urllib.request.urlopen(urllib.request.Request(f"https://flathub.org/api/v2/appstream/{i}", headers=UA), timeout=15)
            return True
        except Exception:
            return False
    repos = [n for a in cat["apps"] for s, n in a["sources"] if s == "repo"]
    fps = [n for a in cat["apps"] for s, n in a["sources"] if s == "flatpak"]
    # the two batches run side by side, each in its own small pool (Flathub stays at a few workers: every error
    # there reads MISSING, so throttling would show false failures); a running count on stderr so a slow
    # archlinux.org doesn't look like a hang, while the report below keeps the catalog's order
    from concurrent.futures import as_completed
    total = len(repos) + len(fps)
    print(f"Checking {len(repos)} packages from the official repos and {len(fps)} Flathub apps online. This can take a few minutes...",
          file=sys.stderr, flush=True)
    on_arch, on_fh, official_errors = {}, {}, {}
    with ThreadPoolExecutor(3) as ex_a, ThreadPoolExecutor(3) as ex_f:
        jobs = {ex_a.submit(arch, n): (on_arch, n) for n in repos}
        jobs.update({ex_f.submit(flathub, n): (on_fh, n) for n in fps})
        for i, fut in enumerate(as_completed(jobs), 1):
            d, n = jobs[fut]
            if d is on_arch:
                d[n], reason = fut.result()
                if reason:
                    official_errors[reason] = official_errors.get(reason, 0) + 1
            else:
                d[n] = fut.result()
            if i % 10 == 0 or i == total:
                print(f"  {i} of {total} checked", file=sys.stderr, flush=True)
    for reason, count in sorted(official_errors.items()):
        print(f"Official repository checks didn't finish ({count}): {reason}", file=sys.stderr)
    bad = incomplete = 0
    ids = set()
    for a in cat["apps"]:
        notes = []
        if a["id"] in ids:
            notes.append("duplicate id")
        ids.add(a["id"])
        if a["cat"] not in cat["categories"]:
            notes.append(f"unknown category {a['cat']}")
        long_card = len(a.get("blurb") or a["desc"]) > 75          # a Discover card shows about three short lines
        if long_card:
            notes.append("card text over 75 characters: add a blurb")
        usable = unsure = 0
        for s, n in a["sources"]:
            if s == "repo":
                here, plain = n in idx, on_arch.get(n)
                notes.append(f"repo:{n} here={'yes ' + idx[n][0] if here else 'NO'} official={'yes' if plain else 'NO' if plain is False else '?'}")
                usable += here or bool(plain)
                unsure += plain is None
            elif s == "aur":
                x = aur.get(n)
                if not x and n in aur_unknown:                     # no answer is not "missing" (same as arch=?)
                    notes.append(f"aur:{n} ?")
                    unsure += 1
                    continue
                notes.append(f"aur:{n} " + (("OUT-OF-DATE " if x.get("OutOfDate") else "") + f"votes={x['NumVotes']}" if x else "MISSING"))
                usable += bool(x)
            elif s == "flatpak":
                notes.append(f"flatpak:{n} {'ok' if on_fh[n] else 'MISSING'}")
                usable += on_fh[n]
            elif s == "vendor":
                r = vendor_recipe(n, cat)
                notes.append(f"vendor:{n} " + (f"ok {r['installer']}" if r else "BAD RECIPE (needs maker, https installer, command, launcher in files)"))
                usable += bool(r)
        flag = "" if usable == len(a["sources"]) and not long_card else "  <-- check"
        if usable == 0:
            flag = "  <-- check (source checks incomplete)" if unsure else "  <-- NOTHING WORKS"
        incomplete += unsure
        bad += bool(flag)
        print(f"{a['id']:16} " + " | ".join(notes) + flag)
    print(f"\n{len(cat['apps'])} apps, {bad} to check")
    if incomplete:
        print(f"{incomplete} source checks incomplete: '?' means the online source didn't answer. "
              "Retry with 'starchaser software verify' when the source is reachable.")
    return 3 if incomplete else 0


# A downloaded installer for another system, by its file ending: what to call that system, in plain words (no other
# distribution's name on screen)
FOREIGN_KINDS = {".deb": "a different kind of Linux", ".rpm": "a different kind of Linux", ".snap": "a different kind of Linux",
                 ".exe": "Windows", ".msi": "Windows", ".dmg": "Mac", ".pkg": "Mac"}

# Windows downloads named by a short form of the app's name: the search uses the name people know ("npp" found only a
# C++ library, QA 2026-11-05). One with no Linux edition searches by what it does instead ("rufus" found only Community
# recipes with look-alike names; "bootable USB" finds checked Flathub apps that write USB drives, QA 2026-11-06).
FOREIGN_SHORT_NAMES = {"npp": "Notepad++", "rufus": "bootable USB"}


def foreign_app_name(file_name: str) -> str:
    return software_websites.foreign_app_name(SoftwareContext(globals()), file_name)


def is_appimage(path: str) -> bool:
    return software_websites.is_appimage(SoftwareContext(globals()), path)


def is_linux_program(path: str) -> bool:
    return software_websites.is_linux_program(SoftwareContext(globals()), path)


# what the AppImage runtime itself prints when it can't start the app inside (not the app's own words)
APPIMAGE_START_ERRORS = re.compile(r"cannot mount appimage|error loading libfuse|fusermount|fuse: device not found", re.I)
# appimagetool asks for its required source without printing a Usage line. Other startup errors (such as a
# missing GUI resource) still aren't evidence of a command-line app.
APPIMAGE_COMMAND_HELP = re.compile(r"^usage:\s|^ERROR: SOURCE is missing\s*$", re.I | re.M)


def appimage_details(path: str, code: int, output: str):
    return software_websites.appimage_details(SoftwareContext(globals()), path, code, output)


def run_appimage(path: str, full_access=False, selected_file=None, privacy_app=None):
    return software_websites.run_appimage(SoftwareContext(globals()), path, full_access, selected_file, privacy_app)


def session_of(pid) -> int:
    return software_websites.session_of(SoftwareContext(globals()), pid)


def app_process(pid: int, launcher: int) -> bool:
    return software_websites.app_process(SoftwareContext(globals()), pid, launcher)


def watch_for_window(p, path: str, wait: int = 30):
    return software_websites.watch_for_window(SoftwareContext(globals()), p, path, wait)


# Apps from websites a person added to their apps (decided 2026-11-07 #42). The AppImage moves to ~/Applications (the
# folder the AppImage project suggests, and one the person sees in Files); its launcher is
# ~/.local/share/applications/appimage-<id>.desktop and its icon ~/.local/share/icons/appimage-<id>.png (or .svg). The
# launcher names its AppImage (X-Starchaser-AppImage), so Software lists it "From a website", and Remove takes those
# three files and nothing else. All of it is the person's own, done as them: no password, no root.
APPIMAGE_DIR = "Applications"
APPIMAGE_ID = re.compile(r"appimage-[a-z0-9][a-z0-9-]{0,59}")
APPIMAGE_ICON_MAX = 4 << 20     # an app icon is a few hundred KB at most
# the AppImage's own launcher keys that carry over; never MimeType (an unchecked app doesn't take over file types)
APPIMAGE_FULL_ACCESS = set()
APPIMAGE_KEYS = ("Name", "GenericName", "Comment", "Categories", "Keywords", "Terminal")
APPIMAGE_ARG = re.compile(r"%[fFuU]|--?[A-Za-z0-9][A-Za-z0-9_.,=-]*")


def appimage_dirs() -> tuple:
    return software_websites.appimage_dirs(SoftwareContext(globals()))


def appimage_unpack(path: str, root: Path, pattern: str) -> None:
    return software_websites.appimage_unpack(SoftwareContext(globals()), path, root, pattern)


def appimage_inside(path: str, tmp: Path, f: Path):
    return software_websites.appimage_inside(SoftwareContext(globals()), path, tmp, f)


def appimage_entry(path: str, tmp: Path) -> tuple:
    return software_websites.appimage_entry(SoftwareContext(globals()), path, tmp)


def appimage_id(stem: str, name: str) -> str:
    return software_websites.appimage_id(SoftwareContext(globals()), stem, name)


def one_line(s: str) -> str:
    return software_websites.one_line(SoftwareContext(globals()), s)


def appimage_changed() -> None:
    return software_websites.appimage_changed(SoftwareContext(globals()))


def appimage_added(path: str) -> str:
    return software_websites.appimage_added(SoftwareContext(globals()), path)


def add_appimage(path: str, window_class: str = "") -> str:
    return software_websites.add_appimage(SoftwareContext(globals()), path, window_class)


def appimage_files(app_id: str) -> list:
    return software_websites.appimage_files(SoftwareContext(globals()), app_id)


def appimage_apps() -> list:
    return software_websites.appimage_apps(SoftwareContext(globals()))


def run_appimage_remove(app_id: str) -> bool:
    return software_websites.run_appimage_remove(SoftwareContext(globals()), app_id)


def offer_add_appimage(path: str, window_class: str) -> None:
    return software_websites.offer_add_appimage(SoftwareContext(globals()), path, window_class)


def flatpak_file_title(path: str) -> str:
    return software_websites.flatpak_file_title(SoftwareContext(globals()), path)


def cmd_flatpak_file(path: str) -> None:
    return software_websites.cmd_flatpak_file(SoftwareContext(globals()), path)


def confirm_appimage_full_access(path: str) -> bool:
    return software_websites.confirm_appimage_full_access(SoftwareContext(globals()), path)


def program_choice(path: str, allow_full_access=False) -> bool:
    return software_websites.program_choice(SoftwareContext(globals()), path, allow_full_access)


def cmd_foreign(path: str) -> None:
    return software_websites.cmd_foreign(SoftwareContext(globals()), path)


def cmd_offer(app_id: str, why: str, remind: bool = False) -> None:
    return software_websites.cmd_offer(SoftwareContext(globals()), app_id, why, remind)


def busy_browser_alternative(app: dict):
    return software_websites.busy_browser_alternative(SoftwareContext(globals()), app)


OPEN_OFFERS = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-offers-open.json"


def open_offers(change=None) -> dict:
    return software_websites.open_offers(SoftwareContext(globals()), change)


def cmd_withdraw(app_id: str) -> None:
    return software_websites.cmd_withdraw(SoftwareContext(globals()), app_id)


def hypr_clients() -> list:
    return software_websites.hypr_clients(SoftwareContext(globals()))


# Exec field codes (the file/URL a launcher would pass, the icon, the name): Open passes none of them
FIELD_CODE = re.compile(r"%[fFuUdDnNickvm]")
# programs that only start the real one: their name says nothing about the window's class
WRAPPERS = {"env", "sh", "bash", "dash", "zsh", "fish", "flatpak", "sudo", "pkexec", "nice", "ionice", "taskset",
            "gamemoderun", "prime-run", "python", "python3", "xdg-open", "exec"}


def exec_argv(line: str) -> list:
    return software_websites.exec_argv(SoftwareContext(globals()), line)


def exec_hint(argv: list) -> str:
    return software_websites.exec_hint(SoftwareContext(globals()), argv)


def in_terminal(entry: dict) -> bool:
    return software_websites.in_terminal(SoftwareContext(globals()), entry)


# the window classes of a terminal starchaser terminal opens: kitty's, and the screen reader's terminal's
TERMINAL_CLASSES = ("kitty", "starchaser-terminal")


def terminal_command(argv: list, hold: bool = False) -> list:
    return software_websites.terminal_command(SoftwareContext(globals()), argv, hold)


def class_matches(cls: str, hints: set) -> bool:
    return software_websites.class_matches(SoftwareContext(globals()), cls, hints)


def has_web_browser(scheme: str = "http") -> bool:
    return software_websites.has_web_browser(SoftwareContext(globals()), scheme)


def reveal_website(previous: str) -> None:
    return software_websites.reveal_website(SoftwareContext(globals()), previous)


def cmd_website(url: str) -> int:
    return software_websites.cmd_website(SoftwareContext(globals()), url)


def cmd_setup(source: str, name: str) -> int:
    return software_websites.cmd_setup(SoftwareContext(globals()), source, name)


def detach_and_place(before, hints, existing=()) -> None:
    return software_websites.detach_and_place(SoftwareContext(globals()), before, hints, existing)


def open_failed(desktop: str, entry: dict, rc: int) -> None:
    return software_websites.open_failed(SoftwareContext(globals()), desktop, entry, rc)


def start_detached(cmd: list, cwd, wait: float):
    return software_websites.start_detached(SoftwareContext(globals()), cmd, cwd, wait)


def cmd_open(desktop: str) -> None:
    return software_websites.cmd_open(SoftwareContext(globals()), desktop)


RUN_KINDS = ("update", "software")
LAST_SEEN = HOME / ".cache/starchaser/last-run-seen"


def last_record(kind: str):
    return software_queue.last_record(SoftwareContext(globals()), kind)


def seen_keys() -> dict:
    return software_queue.seen_keys(SoftwareContext(globals()))


def run_key(rec) -> str:
    return software_queue.run_key(SoftwareContext(globals()), rec)


def run_alive(rec) -> bool:
    return software_queue.run_alive(SoftwareContext(globals()), rec)


def terminal_commands(names) -> list:
    return software_queue.terminal_commands(SoftwareContext(globals()), names)


def terminal_words(cmds) -> str:
    return software_queue.terminal_words(SoftwareContext(globals()), cmds)


def preferred_launchers(shown, name, catalog=None):
    return software_queue.preferred_launchers(SoftwareContext(globals()), shown, name, catalog)


def shown_launchers(source: str, name: str) -> list:
    return software_queue.shown_launchers(SoftwareContext(globals()), source, name)


def cmd_run_watch(since: int) -> None:
    return software_queue.cmd_run_watch(SoftwareContext(globals()), since)


def cmd_last_run(kind: str) -> None:
    return software_queue.cmd_last_run(SoftwareContext(globals()), kind)


def cmd_last_run_seen(kind: str, key: str = "") -> None:
    return software_queue.cmd_last_run_seen(SoftwareContext(globals()), kind, key)


# --------------------------------------------------------------------------- the install queue
# Apps picked while another one installs wait in a queue and install one after another (decided 2026-11-04:
# qa/decisions/decisions-2026-11-04.md #3). Each one installs through `run`, exactly as a single install does: its
# own source's path and checks, the root helper through pkexec for system apps, none for Flathub. The password is
# the sitting's (50-starchaser-software.rules), so a batch asks once; nothing here keeps or passes a password.
# A queue started with the password finishes without asking again however long it runs (decided 2026-11-05:
# qa/decisions/decisions-2026-11-05.md #2): root's grant names this helper (queue-run) while it lives, so its runs
# must stay its children (queue_install's Popen), and it exits when no app waits, which ends that.
# The queue runs in a helper of its own (queue-run), so closing Settings doesn't stop it, and lives in the login
# person's state folder, so waiting apps survive sign-out and restart.
RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
QUEUE = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser/software-queue.json"
QUEUE_LOCK = RUNTIME / "starchaser-software-queue.lock"          # held while the queue is read and changed
QUEUE_RUNNER = RUNTIME / "starchaser-software-queue-runner.lock"  # held by the queue's helper for as long as it runs
RUN_LOCK = RUNTIME / "starchaser-software-run.lock"              # shared by every run; the queue waits until it's free
QUEUE_ENV = "STARCHASER_SOFTWARE_QUEUE"                          # set for a run the queue started
QUEUE_LOG = 200                                                  # log lines kept per app, for Show details
QUEUE_WAITING = ("waiting", "installing")
TITLE = re.compile(r"[^\x00-\x1f\x7f]{1,100}")
FIREWALL_ID = re.compile(r"[A-Za-z0-9._-]{0,64}")
_run_lock = None


def hold_run_lock() -> None:
    return software_queue.hold_run_lock(SoftwareContext(globals()))


def queue_read() -> dict:
    return software_queue.queue_read(SoftwareContext(globals()))


def queue_write(s: dict) -> None:
    return software_queue.queue_write(SoftwareContext(globals()), s)


def queue_change(fn) -> dict:
    return software_queue.queue_change(SoftwareContext(globals()), fn)


def queue_runner_alive() -> bool:
    return software_queue.queue_runner_alive(SoftwareContext(globals()))


QUEUE_CHILD = None


def finish_queue_command() -> None:
    return software_queue.finish_queue_command(SoftwareContext(globals()))


def queue_start_runner(s: dict) -> None:
    return software_queue.queue_start_runner(SoftwareContext(globals()), s)


def queue_item(s: dict, item_id: int):
    return software_queue.queue_item(SoftwareContext(globals()), s, item_id)


def cmd_queue_add(source: str, name: str, title: str, firewall: str = "") -> None:
    return software_queue.cmd_queue_add(SoftwareContext(globals()), source, name, title, firewall)


def queue_keep_page_run(source: str, names: list, result: dict) -> None:
    return software_queue.queue_keep_page_run(SoftwareContext(globals()), source, names, result)


def cmd_queue_remove(item_id: int) -> None:
    return software_queue.cmd_queue_remove(SoftwareContext(globals()), item_id)


def cmd_queue_retry(item_id: int) -> None:
    return software_queue.cmd_queue_retry(SoftwareContext(globals()), item_id)


def cmd_queue_clear() -> None:
    return software_queue.cmd_queue_clear(SoftwareContext(globals()))


def cmd_queue_seen() -> None:
    return software_queue.cmd_queue_seen(SoftwareContext(globals()))


def cmd_queue_status() -> None:
    return software_queue.cmd_queue_status(SoftwareContext(globals()))


def queue_turn_blocker(source: str) -> str:
    return software_queue.queue_turn_blocker(SoftwareContext(globals()), source)


def queue_update(item_id: int, **fields) -> dict:
    return software_queue.queue_update(SoftwareContext(globals()), item_id, **fields)


def queue_install(item: dict) -> dict:
    return software_queue.queue_install(SoftwareContext(globals()), item)


def queue_notify(items: list) -> None:
    return software_queue.queue_notify(SoftwareContext(globals()), items)


def cmd_queue_run() -> None:
    return software_queue.cmd_queue_run(SoftwareContext(globals()))


def main(argv):
    cmd = argv[0] if argv else ""
    if cmd in ("details", "app-action", "inventory", "import-plan", "import-add", "answer", "screenshots", "release-notes", "storage", "cleanup", "request-install", "requests", "cancel-request", "recent", "account", "recipe-review", "request-review", "migrate-website", "delete-leftover", "recipe-reviewed"):
        import types
        import software_apps
        try:
            if software_apps.handle(types.SimpleNamespace(**globals()), argv):
                return
        except (ValueError, OSError, subprocess.SubprocessError) as error:
            print(json.dumps({"ok": False, "error": str(error)}))
            sys.exit(1)
    if cmd in ("catalog", "icons", "installed", "verify") and len(argv) > 1:
        sys.exit(takes_nothing_after("starchaser software", cmd, argv))
    if cmd == "plan" and len(argv) == 3:
        source, name = argv[1:]
        if source not in ("repo", "aur", "flatpak"):
            sys.exit(usage_error("starchaser software", f"unknown source: {source}", "plan <source> <name>", ("repo", "aur", "flatpak")))
        pattern = FLATPAK_ID if source == "flatpak" else NAME
        if not pattern.fullmatch(name):
            label = "Flatpak app ID" if source == "flatpak" else "package name"
            sys.exit(usage_error("starchaser software", f"{name!r} is not a valid {label}", "plan <source> <name>"))
    if cmd == "aur-info" and len(argv) == 2 and not NAME.fullmatch(argv[1]):
        # an empty or impossible name is missing input, not a Community recipe that doesn't exist
        sys.exit(usage_error("starchaser software", f"{argv[1]!r} is not a valid package name", "aur-info <package>"))
    if cmd == "remove-plan" and len(argv) == 3 and argv[1] in ("repo", "aur", "flatpak", "vendor", "appimage", "webapp", "terminalapp") and (FLATPAK_ID if argv[1] == "flatpak" else NAME).fullmatch(argv[2]):
        cmd_remove_plan(argv[1], argv[2])
    elif cmd == "catalog":
        cmd_catalog()
    elif cmd == "plan-ready" and len(argv) == 1:
        cmd_plan_ready()
    elif cmd == "app" and len(argv) == 2 and NAME.fullmatch(argv[1]):
        cmd_catalog(argv[1])
    elif cmd == "search" and " ".join(argv[1:]).strip():
        cmd_search(" ".join(argv[1:]))
    elif cmd == "plan" and len(argv) == 3 and argv[1] in ("repo", "aur") and NAME.fullmatch(argv[2]):
        cmd_plan(argv[1], argv[2])
    elif cmd == "plan" and len(argv) == 3 and argv[1] == "flatpak" and FLATPAK_ID.fullmatch(argv[2]):
        cmd_plan_flatpak(argv[2])
    elif cmd == "aur-info" and len(argv) == 2:
        answers, error, _, _ = aur_lookup([argv[1]])
        x = answers.get(argv[1])
        if not x:
            reason = f"no Community recipe called {argv[1]}"
            if error:
                reason = {"rate-limited": "Community recipes are busy right now. Try again later.",
                          "unreachable": "couldn't reach Community recipes. Check your connection and try again."}.get(
                              error, "couldn't look up Community recipes. Try again later.")
            print(json.dumps({"ok": False, "errors": reason}))
            print(f"starchaser software: {reason}", file=sys.stderr)
            sys.exit(1)
        print(json.dumps(aur_summary(x)))
    elif cmd == "icons":
        cmd_icons()
    elif cmd == "last-run" and len(argv) <= 2 and (len(argv) == 1 or argv[1] in RUN_KINDS):
        cmd_last_run(argv[1] if len(argv) == 2 else "")
    elif cmd == "last-run-seen" and len(argv) <= 2 and (len(argv) == 1 or argv[1] in RUN_KINDS):
        cmd_last_run_seen(argv[1] if len(argv) == 2 else "")
    elif cmd == "last-run-seen" and len(argv) == 3 and argv[1] in RUN_KINDS and re.fullmatch(r"[\w.-]{1,64}", argv[2]):
        cmd_last_run_seen(argv[1], argv[2])
    elif cmd == "installed":
        cmd_installed(local_only=True)
    elif cmd == "run" and len(argv) >= 4:
        args = argv[1:]
        update_first = args[:1] == ["--update-first"]
        args = args[update_first:]
        clear = args[:1] == ["--clear-stale-lock"]
        args = args[clear:]
        replace = args[0].split("=", 1)[1].split(",") if args and args[0].startswith("--replace=") else []
        args = args[bool(replace):]
        if len(args) < 3:
            sys.exit(software_usage_error(argv))
        remove_plan = args.pop(0).split("=", 1)[1].split(",") if args and args[0].startswith("--remove-plan=") else None
        delete_data = args[:1] == ["--delete-data"]
        if delete_data: args.pop(0)
        cmd_run(args[0], args[1], args[2:], clear_stale=clear, replace=replace, remove_plan=remove_plan, delete_data=delete_data, update_first=update_first)
    elif cmd == "firewall-draft" and len(argv) in (3, 4):
        cmd_firewall_draft(*argv[1:])
    elif cmd == "verify":
        import os
        import signal

        def stop(signum, frame):
            # Ctrl-C gives the prompt back at once: the check pools join on the way out of the run, and their
            # rate-limited calls are what made an interrupted verify look frozen
            print("Stopped.", file=sys.stderr, flush=True)
            os._exit(130)
        signal.signal(signal.SIGINT, stop)
        sys.exit(cmd_verify())
    elif cmd == "open" and len(argv) == 2 and re.fullmatch(r"[A-Za-z0-9._@+-]{1,200}", argv[1]):
        cmd_open(argv[1])
    elif cmd == "website" and len(argv) == 2:
        sys.exit(cmd_website(argv[1]))
    elif cmd == "setup" and len(argv) == 3 and argv[1] in ("repo", "aur") and NAME.fullmatch(argv[2]):
        sys.exit(cmd_setup(argv[1], argv[2]))
    elif cmd == "windows" and len(argv) == 3 and (argv[1] in ("repo", "aur") and NAME.fullmatch(argv[2])
                                                  or argv[1] == "flatpak" and FLATPAK_ID.fullmatch(argv[2])):
        print(json.dumps({"open": len(app_windows(argv[1], argv[2]))}))
    elif cmd == "windows" and len(argv) == 3 and argv[1] in ("appimage", "webapp", "terminalapp") and NAME.fullmatch(argv[2]):
        print(json.dumps({"open": len(app_windows(argv[1], argv[2]))}))
    elif cmd == "windows" and len(argv) == 3 and argv[1] == "vendor" and NAME.fullmatch(argv[2]):
        print(json.dumps({"open": 0}))              # a maker-installed app here is a terminal tool: no windows of its own
    elif cmd == "offer" and len(argv) == 4 and argv[1] == "--remind":
        cmd_offer(argv[2], argv[3], remind=True)
    elif cmd == "offer" and len(argv) == 3 and not argv[1].startswith("-"):
        cmd_offer(argv[1], argv[2])
    elif cmd == "withdraw" and len(argv) == 2:
        cmd_withdraw(argv[1])
    elif cmd == "program-card" and len(argv) == 2 and argv[1]:
        sys.exit(0 if program_choice(argv[1]) else 1)
    elif cmd == "launch-website" and len(argv) in (2, 3) and APPIMAGE_ID.fullmatch(argv[1]):
        files = appimage_files(argv[1])
        entry = desktop_entry(appimage_dirs()[1] / (argv[1] + ".desktop"))
        path = entry.get("X-Starchaser-AppImage", "")
        if not path or Path(path) not in files:
            sys.exit("This website app is no longer in your apps.")
        run_appimage(path, full_access=entry.get("X-Starchaser-FullAccess") == "true", selected_file=argv[2] if len(argv) == 3 else None,
                     privacy_app='native:' + argv[1] + '.desktop')
    elif cmd == "foreign" and len(argv) == 2 and argv[1]:
        if Path(argv[1]).suffix.lower() in (".deb", ".rpm", ".snap", ".dmg", ".pkg"):
            # Guidance can wait in the bell indefinitely. Release Files' open request while
            # an independent worker keeps the Search Software and Close actions available.
            subprocess.Popen([sys.executable, __file__, "foreign-notice", argv[1]],
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                             stderr=subprocess.DEVNULL, start_new_session=True)
        else:
            cmd_foreign(argv[1])
    elif cmd == "foreign-notice" and len(argv) == 2 and argv[1]:
        cmd_foreign(argv[1])
    elif cmd == "run-watch" and len(argv) == 2 and argv[1].isdigit():
        cmd_run_watch(int(argv[1]))
    elif cmd == "queue" and len(argv) == 1:
        cmd_queue_status()
    elif cmd == "queue" and len(argv) in (5, 6) and argv[1] == "add" and TITLE.fullmatch(argv[4]) \
            and FIREWALL_ID.fullmatch(argv[5] if len(argv) == 6 else "") \
            and (argv[2] in ("repo", "aur", "vendor") and NAME.fullmatch(argv[3]) or argv[2] == "flatpak" and FLATPAK_ID.fullmatch(argv[3])):
        cmd_queue_add(argv[2], argv[3], argv[4], argv[5] if len(argv) == 6 else "")
    elif cmd == "queue" and len(argv) == 3 and argv[1] in ("remove", "retry") and argv[2].isdigit():
        (cmd_queue_remove if argv[1] == "remove" else cmd_queue_retry)(int(argv[2]))
    elif cmd == "queue" and len(argv) == 2 and argv[1] == "clear":
        cmd_queue_clear()
    elif cmd == "queue" and len(argv) == 2 and argv[1] == "seen":
        cmd_queue_seen()
    elif cmd == "queue-run" and len(argv) == 1:
        cmd_queue_run()
    else:
        sys.exit(software_usage_error(argv))


def software_usage_error(argv):
    commands = {
        **{name: (name, (), ()) for name in ("catalog", "icons", "installed", "verify")},
        "app": ("app <catalog-id>", ("catalog ID",), ()),
        "search": ("search <words>", ("search words",), ()),
        "plan": ("plan <source> <name>", ("source", "package name or app ID"), ("repo", "aur", "flatpak")),
        "plan-ready": ("plan-ready", (), ()),
        "aur-info": ("aur-info <package>", ("package name",), ()),
        "run": ("run [--update-first] [--clear-stale-lock] <action> <source> <name> [name ...]",
                ("action", "source", "package name or app ID"), ("install", "remove", "repair", "repo", "aur", "flatpak", "vendor", "appimage", "webapp", "terminalapp")),
        "last-run": ("last-run [kind]", (), RUN_KINDS),
        "last-run-seen": ("last-run-seen [kind [key]]", (), RUN_KINDS),
        "firewall-draft": ('firewall-draft <app-id> "<app-name>" [<asked-from>]', ("app ID", "app name"), ()),
        "open": ("open <desktop-id>", ("desktop ID",), ()),
        "setup": ("setup <source> <name>", ("source", "package name"), ("repo", "aur")),
        "windows": ("windows <source> <name>", ("source", "package name or app ID"), ("repo", "aur", "flatpak", "vendor", "appimage", "webapp", "terminalapp")),
        "offer": ('offer [--remind] <catalog-id> "<reason>"', ("catalog ID", "reason"), ()),
        "withdraw": ("withdraw <catalog-id>", ("catalog ID",), ()),
        "foreign": ("foreign <file>", ("file",), ()),
        "program-card": ("program-card <file>", ("file",), ()),
        "run-watch": ("run-watch <start time>", ("start time",), ()),
        "queue": ('queue [add <source> <name> "<title>" [firewall-app-id] | remove <id> | retry <id> | clear | seen]', (),
                  ("add", "remove", "retry", "clear", "seen")),
        "queue-run": ("queue-run", (), ()),
    }
    flags = ("--update-first", "--clear-stale-lock") if argv[:1] == ["run"] else ("--remind",) if argv[:1] == ["offer"] else ()
    return command_usage_error("starchaser software", [x for x in argv if x not in flags and not (argv[:1] == ["run"] and x.startswith("--replace="))], commands)


if __name__ == "__main__":
    # A reader such as head may close stdout after it has all it needs.
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    if sys.argv[1:2] == ["help"] or any(a in ("-h", "--help") for a in sys.argv[1:]):      # usage on request is not an error
        print(__doc__)
        sys.exit(0)
    main(sys.argv[1:])
    finish_queue_command()
