#!/usr/bin/env python3
"""安装之后的首次配置：备齐词库、准备状态目录、把输入法加入当前的输入法列表。

这三步此前都没有产品侧的入口。词库要么在配置阶段用 -DMSIME_ENGINE_RESOURCES 随包装好，
要么只能在仓库检出里跑一个 Cargo 示例去取——也就是说一个只拿到安装包的用户没有任何办法
把词库凑齐，而没有词库输入法一个候选都出不来。状态目录同样：msime-linux-prepare 要两个
绝对路径，用户得先知道该给哪两个。

这里不重新实现校验和准备：词库按已安装的 desktop-dictionary.lock.json 逐个核对名称、大小
和 SHA-256，状态交给 msime-linux-prepare。下载默认不发生，必须显式 --download。

Windows 安装程序注册 TSF profile，装完输入法就出现在输入法列表里；这里对应的是在状态目录就绪后把输入法加进正在运行的 Fcitx5 或 IBus 的列表。任何一步失败都退回到打印手动步骤，不影响已经准备好的状态。

Windows 卸载程序注销 TSF profile 和类别，输入法随之从列表里消失，并删除水杉留下的全部状态；对应的是 --unregister：卸载时（.deb 的 prerm、CMake 卸载）在删除文件之前把输入法从这些列表里移除，再把宿主改过的桌面候选面板设置（Fcitx5 classicui 的主题、字体和滚轮翻页，IBus 面板的字体）恢复成接管之前的值——用户之后自己改过的不动——并删除水杉生成的 Fcitx5 主题。只做这些，不准备状态也不下载。

--update 对应 Windows 安装程序升级时的用户词库回放。随包提供词库的安装由包管理器换掉词库，宿主启动时自己切换代次；自行下载的词库没有人替换，升级抬高词库版本后宿主只能继续用旧的。--update 读出已有状态记录的词库目录，按已安装的词库锁核对；不符时加 --download 在旁边另建一份新词库目录，与旧目录一致的几项直接链接过去，只取回缺失或不符的几项，旧目录一个文件都不动。随后请两个宿主关掉输入会话，用 msime-linux-prepare --refresh 切到新代次并回放用户词库，再让它们重新打开。已有状态时给 --download 即视为 --update。
"""
from __future__ import annotations

import argparse
import ast
import contextlib
import fcntl
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
from pathlib import Path

CHUNK = 1024 * 1024
# 国内镜像（Cloudflare R2，见 msime-web README「国内镜像」）：`<前缀><原地址>`，没缓存过的发布资产由镜像从 GitHub 取一次后留存。国内直连 GitHub 下载词库常常只有几十 KB/s。MSIME_DOWNLOAD_MIRROR 可以换成别的前缀，设为空串则只用原地址（测试靠它不出网）。
MIRROR_PREFIX = os.environ.get("MSIME_DOWNLOAD_MIRROR", "https://dl.msime.app/gh/")
# IBus, Fcitx5 and the host refresh path all reject runtime-options.json above this size.
RUNTIME_OPTIONS_LIMIT = 16 * 1024
# The hosts cap the shared panel restore record before parsing it.
PANEL_RESTORE_LIMIT = 64 * 1024
# Each registration step is a local D-Bus or dconf round trip; a wedged daemon must not hold up the end of setup.
COMMAND_TIMEOUT = 10
DOWNLOAD_TIMEOUT = 60
FCITX5_INPUT_METHOD = "msime"
FCITX5_NAME = "水杉输入法"
IBUS_ENGINE = "msime-linux"
# The IBus <longname>, the same name the Windows TSF profile registers.
IBUS_NAME = "Metasequoia 水杉输入法"
FCITX5_CONTROLLER = [
    "gdbus", "call", "--session", "--dest", "org.fcitx.Fcitx5", "--object-path", "/controller", "--method",
]
FCITX5_INTERFACE = "org.fcitx.Fcitx.Controller1"
FCITX5_BUS_NAME = "org.fcitx.Fcitx5"
GNOME_SOURCES = ("org.gnome.desktop.input-sources", "sources")
IBUS_PRELOAD = ("org.freedesktop.ibus.general", "preload-engines")
# The desktop panel settings the hosts take over, and the record of what they replaced (src/candidates/PanelRestoreRecord.h).
PANEL_RESTORE_FILE = "msime-client/panel-restore.json"
FCITX5_CLASSICUI_URI = "fcitx://config/addon/classicui"
FCITX5_THEME = "msime"
# Fcitx5's stock themes, the only ones the hosts take over (src/candidates/CandidateFcitxTheme.h), for the options that name a theme.
FCITX5_STOCK_THEMES = {"Theme": "default", "DarkTheme": "default-dark"}
IBUS_PANEL = "org.freedesktop.ibus.panel"
ANONYMOUS_ACCOUNT_FILES = {"anonymous-account.json", "anonymous-session.json"}


def data_home() -> Path:
    value = os.environ.get("XDG_DATA_HOME")
    return Path(value) if value else Path.home() / ".local/share"


def config_home() -> Path:
    value = os.environ.get("XDG_CONFIG_HOME")
    return Path(value) if value else Path.home() / ".config"


def install_prefix() -> Path:
    """本脚本所属的安装前缀，按自身真实路径推出，支持自定义前缀。"""
    return Path(__file__).resolve().parent.parent


def lock_candidates(prefix: Path) -> list[Path]:
    """已安装的词库锁文件可能在哪。显式环境变量优先。"""
    paths = []
    override = os.environ.get("MSIME_DICTIONARY_LOCK")
    if override:
        paths.append(Path(override))
    paths.append(prefix / "share/msime-client/desktop-dictionary.lock.json")
    for directory in os.environ.get("XDG_DATA_DIRS", "/usr/local/share:/usr/share").split(":"):
        if directory:
            paths.append(Path(directory) / "msime-client/desktop-dictionary.lock.json")
    return paths


def resource_candidates(prefix: Path) -> list[Path]:
    """已有词库目录可能在哪，按优先级。用户自己的那份排在随包安装的后面，
    因为随包的那份与本次安装同源。"""
    return [
        prefix / "share/msime-client/resources",
        data_home() / "msime-client/resources",
    ]


def digest(path: Path) -> str:
    value = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(CHUNK), b""):
            value.update(block)
    return value.hexdigest()


# The Engine's helpcode tables live in this subdirectory of the resource directory; the host's verification lets it through (crates/client-core/src/resources.rs).
HELPCODE_DIRECTORY = "helpcodes"

HELPCODE_FILES = (
    "helpcode.txt", "zrm_helpcode_big_unique.txt", "shouyou2_0_helpcode.txt",
    "shouyouplus_helpcode.txt", "xiaohe_helpcode.txt", "jiajia_helpcode.txt",
    "wubi86_helpcode.txt",
)


def install_helpcodes(prefix: Path, resources: Path) -> None:
    """补齐随包内置表，保留用户自定义表；不沿目标目录链接写入。"""
    source = prefix / "share/msime-client/resources" / HELPCODE_DIRECTORY
    target = resources / HELPCODE_DIRECTORY
    if source == target:
        return
    if resources.is_symlink() or target.is_symlink():
        raise OSError("辅助码目标目录不能是符号链接")
    for name in HELPCODE_FILES:
        table = source / name
        if table.is_symlink() or not table.is_file():
            raise OSError(f"安装包缺少辅助码表 {table}，请重新安装")
    target.mkdir(exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".helpcodes-", dir=target) as staging_name:
        staging = Path(staging_name)
        for name in HELPCODE_FILES:
            shutil.copyfile(source / name, staging / name)
        for name in HELPCODE_FILES:
            (staging / name).replace(target / name)


def unexpected_entries(directory: Path, lock: dict) -> list[str]:
    """目录里锁之外的条目。宿主要求词库目录恰好是锁里那几项，多一个文件就拒绝整份词库；下载补不掉它们，得由用户移走。"""
    if not directory.is_dir():
        return []
    names = {artifact["name"] for artifact in lock["artifacts"]}
    return [
        f"{entry.name} 不在词库锁中或不是普通文件，宿主会拒绝这份词库；请把它移出 {directory}"
        for entry in sorted(os.scandir(directory), key=lambda item: item.name)
        if not (entry.name == HELPCODE_DIRECTORY and entry.is_dir(follow_symlinks=False))
        and (entry.name not in names or not entry.is_file(follow_symlinks=False))
    ]


def verify_directory(directory: Path, lock: dict) -> list[str]:
    """锁文件与目录不符之处，逐条列出；空列表表示这份词库可用。

    与宿主的校验一致，锁之外的条目也算：升级去掉某项词库时旧文件会留在下载目录里，在这里报出来，而不是等宿主拒绝后只剩一句笼统的失败。"""
    problems = unexpected_entries(directory, lock)
    for artifact in lock["artifacts"]:
        name = artifact["name"]
        path = directory / name
        if not path.is_file():
            problems.append(f"缺少 {name}")
            continue
        size = path.stat().st_size
        if size != artifact["size"]:
            problems.append(f"{name} 大小不符：期望 {artifact['size']}，实际 {size}")
            continue
        if digest(path) != artifact["sha256"]:
            problems.append(f"{name} SHA-256 不符")
    return problems


def fetch(url: str, destination: Path, maximum: int) -> None:
    try:
        # 镜像可能拒绝 Python 默认客户端标识；每次下载明确声明项目身份。
        request = urllib.request.Request(url, headers={"User-Agent": "msime-linux-setup"})
        with urllib.request.urlopen(request, timeout=DOWNLOAD_TIMEOUT) as response, destination.open("wb") as handle:
            advertised = response.headers.get("Content-Length")
            if advertised is not None:
                try:
                    if int(advertised) > maximum:
                        raise SystemExit(f"下载响应超过 {maximum} 字节限制")
                except ValueError:
                    pass
            size = 0
            while True:
                block = response.read(CHUNK)
                if not block:
                    break
                size += len(block)
                if size > maximum:
                    raise SystemExit(f"下载响应超过 {maximum} 字节限制")
                handle.write(block)
    except BaseException:
        with contextlib.suppress(FileNotFoundError):
            destination.unlink()
        raise


def fetch_verified(artifact: dict, destination: Path) -> None:
    """先国内镜像、再锁里的原地址：镜像下载失败、超出大小或 SHA-256 不符就换原地址。原地址也不行时照旧报错：网络错误交给调用方报「词库目录未改动」，校验不符直接中止。"""
    url = artifact["url"]
    if MIRROR_PREFIX:
        try:
            fetch(MIRROR_PREFIX + url, destination, artifact["size"])
            if digest(destination) == artifact["sha256"]:
                return
            print(f"国内镜像上的 {artifact['name']} 校验不符，改从原地址下载", file=sys.stderr)
        except (OSError, SystemExit) as error:
            print(f"国内镜像下载 {artifact['name']} 失败（{error}），改从原地址下载", file=sys.stderr)
        with contextlib.suppress(FileNotFoundError):
            destination.unlink()
    fetch(url, destination, artifact["size"])
    if digest(destination) != artifact["sha256"]:
        raise SystemExit(f"{artifact['name']} 校验失败，已中止；目标目录未改动")


def download_artifacts(lock: dict, directory: Path) -> None:
    """按锁下载并校验，全部通过后才发布到目标目录。校验不过或下载中断即中止，目标目录一个文件都不动，不留半份词库。

    先在同一文件系统的临时目录里备齐并逐个校验，再逐个改名发布。改名替换的是目录项而不是文件内容，所以更新时从旧词库目录硬链接过来的文件被替换后，旧目录里那一份不受影响。"""
    pending = [
        artifact
        for artifact in lock["artifacts"]
        if not ((directory / artifact["name"]).is_file() and digest(directory / artifact["name"]) == artifact["sha256"])
    ]
    # Checked before the first request, so a lock the setup cannot satisfy costs no download.
    unreachable = [artifact["name"] for artifact in pending if not artifact.get("url")]
    if unreachable:
        raise SystemExit(f"{'、'.join(unreachable)} 在词库锁里没有下载地址，无法取回；请用 --resources 指向一份已备齐的词库目录。")
    directory.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(dir=directory.parent) as staging_name:
        staging = Path(staging_name)
        verified = []
        for artifact in pending:
            name = artifact["name"]
            staged = staging / name
            print(f"下载 {name}")
            fetch_verified(artifact, staged)
            verified.append((staged, directory / name))
        for staged, target in verified:
            staged.replace(target)


def prepare_command(command: Path, resources: Path, state: Path, cloud_candidates: bool) -> list[str]:
    """云候选新装默认关闭，与 Windows 安装程序的「联网功能」页一样，在首次准备时由用户决定是否打开。"""
    flags = ["--cloud-candidates"] if cloud_candidates else []
    return [str(command), *flags, str(resources), str(state)]


def prepare_executable(prefix: Path) -> Path:
    command = prefix / "bin/msime-linux-prepare"
    if command.is_file():
        return command
    return Path(shutil.which("msime-linux-prepare") or "msime-linux-prepare")


def prepare_state(prefix: Path, resources: Path, state: Path, cloud_candidates: bool) -> None:
    command = prepare_executable(prefix)
    result = subprocess.run(prepare_command(command, resources, state, cloud_candidates), check=False)
    if result.returncode != 0:
        raise SystemExit("准备状态目录失败，见上面的输出")


def anonymous_account_state(state: Path) -> bool:
    """Allow the installer-created account files to coexist with first-run state."""
    if not state.is_dir() or state.is_symlink():
        return False
    try:
        entries = list(state.iterdir())
    except OSError:
        return False
    return bool(entries) and all(
        entry.name in ANONYMOUS_ACCOUNT_FILES and entry.is_file() and not entry.is_symlink()
        for entry in entries
    )


def fetch_missing(lock: dict, resources: Path, in_use: Path | None = None) -> list[str]:
    """按锁取回缺失或不符的词库，返回取回之后仍然不符之处。网络失败时目标目录不变；有下载补不掉的多余条目时不下载。in_use 是更新时输入法正在用、这里不写入的那份目录。"""
    unexpected = unexpected_entries(resources, lock)
    if unexpected:
        return unexpected
    try:
        download_artifacts(lock, resources)
    except OSError as error:
        raise SystemExit(f"下载失败：{error}\n词库目录未改动：{in_use or resources}")
    return verify_directory(resources, lock)


def print_problems(heading: str, problems: list[str]) -> None:
    print(heading, file=sys.stderr)
    for problem in problems[:5]:
        print(f"  {problem}", file=sys.stderr)


# msime-linux-prepare --refresh exits 3 when the host library still finds the recorded dictionaries outdated.
REFRESH_OUTDATED = 3


def read_options(options_file: Path) -> dict:
    try:
        # Open the final component without following a replacement symlink. The
        # descriptor remains tied to the checked file even if an attacker swaps
        # the path while it is being read.
        flags = os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW
        with os.fdopen(os.open(options_file, flags), "rb") as handle:
            raw = handle.read(RUNTIME_OPTIONS_LIMIT + 1)
        if len(raw) > RUNTIME_OPTIONS_LIMIT:
            raise ValueError(f"文件超过 {RUNTIME_OPTIONS_LIMIT} 字节限制")
        document = json.loads(raw.decode())
    except (OSError, ValueError) as error:
        raise SystemExit(f"无法读取 {options_file}：{error}")
    if not isinstance(document, dict):
        raise SystemExit(f"{options_file} 不是 msime-linux-prepare 生成的配置")
    return document


def recorded_path(document: dict, key: str, options_file: Path) -> Path:
    """已有状态记录的某个目录：resources 是宿主校验、Engine 读取的那份词库，user_data 是输入会话持锁的用户目录。"""
    value = document.get(key)
    if not isinstance(value, str) or not Path(value).is_absolute():
        raise SystemExit(f"{options_file} 没有记录 {key}，不是 msime-linux-prepare 生成的配置")
    return Path(value)


def updatable(path: Path, prefix: Path) -> bool:
    """只更新当前用户自己下载的那份词库。随本次安装提供的词库归包管理器，哪怕装在用户可写的前缀下；别人的目录同样不碰。装在 ~/.local 这类前缀下时，随包词库的位置就是首次配置的下载目录，那里的词库是用户自己下载的，不算随包。目录不在时看它的上一级，下载会把它建出来。"""
    packaged = (prefix / "share/msime-client/resources").resolve()
    if path.resolve() == packaged and packaged != (data_home() / "msime-client/resources").resolve():
        return False
    existing = path if path.exists() else path.parent
    try:
        return existing.is_dir() and existing.stat().st_uid == os.geteuid() and os.access(existing, os.W_OK)
    except OSError:
        return False


def link_or_copy(source: str, target: str) -> None:
    try:
        os.link(source, target)
    except OSError:
        shutil.copy2(source, target)


def staged_resources(resources: Path, lock: dict) -> Path:
    """新版本词库的目录：与正在使用的那份并列，按锁的内容命名，中断后再运行会接着用同一个目录。

    正在使用的目录不能原地更新：旧代次的会话每次查询都按路径打开其中的 msime-others.db 等文件，换掉其中几项它就读到新旧混杂的一份，切换失败时也无法退回。与锁一致的文件直接硬链接过来，只有缺失或不符的几项需要下载；下载总是改名替换，不写已有文件，所以链接不会改到旧目录。"""
    tag = hashlib.sha256(
        "\n".join(f"{artifact['name']}:{artifact['sha256']}" for artifact in lock["artifacts"]).encode()
    ).hexdigest()[:16]
    target = resources.parent / f"resources-{tag}"
    if target.resolve() == resources.resolve():
        # The recorded directory already carries this lock's name yet does not match it; stage beside it all the same.
        target = Path(tempfile.mkdtemp(prefix=f"resources-{tag}-", dir=resources.parent))
    target.mkdir(parents=True, exist_ok=True)
    for artifact in lock["artifacts"]:
        source, staged = resources / artifact["name"], target / artifact["name"]
        if staged.exists() or not source.is_file() or source.stat().st_size != artifact["size"]:
            continue
        link_or_copy(str(source), str(staged))
    helpcodes = resources / HELPCODE_DIRECTORY
    if helpcodes.is_dir() and not helpcodes.is_symlink() and not (target / HELPCODE_DIRECTORY).exists():
        shutil.copytree(helpcodes, target / HELPCODE_DIRECTORY, copy_function=link_or_copy)
    return target


# The lease the settings window writes for dictionary maintenance (platforms/linux/src/core/DictionaryQuiesceLease.h): while it is live both hosts finish the composition, close their sessions and open no new ones. They ignore an expiry more than 30 s out, so it is written for less and renewed while held.
QUIESCE_LEASE = ".msime-dictionary-quiesce"
QUIESCE_LEASE_SECONDS = 20
QUIESCE_RENEW_SECONDS = 5
# 每个输入会话都以共享方式持有用户目录上的这把锁（见 `crates/client-services/src/dictionary/access.rs`），所以能以独占方式拿到它，就证明会话都已退出，同时也能阻止新会话打开。
ACCESS_LOCK = ".msime-dictionary-access.lock"
# Long enough for the IBus host's one-second lease check to come round twice, the same budget the settings window gives it.
QUIESCE_BUDGET = 2.5
# The IBus host rereads runtime-options.json within 100 ms when its directory monitor works and every 5 s otherwise; a session it opened before that would go back to the previous generation.
IBUS_OPTIONS_RELOAD = 6


class HostsBusy(Exception):
    """An input session still held the dictionaries when the budget ran out."""


@contextlib.contextmanager
def hosts_held_off(user_data: Path):
    """Keep both hosts' sessions closed on user_data while the body runs, as the settings window does for dictionary maintenance.

    The refresh replays the user journal into the new generation once. A session left open would keep learning into the previous generation and the journal after that replay, and nothing replays it again, so those words would be missing from the new dictionaries. A missing user directory has no session to close."""
    if not user_data.is_dir():
        yield
        return
    lease = user_data / QUIESCE_LEASE

    def publish() -> None:
        staged = lease.with_name(f"{QUIESCE_LEASE}.{os.getpid()}")
        staged.write_text(f"{int((time.time() + QUIESCE_LEASE_SECONDS) * 1000)}\n")
        staged.replace(lease)

    stop = threading.Event()

    def renew() -> None:
        while not stop.wait(QUIESCE_RENEW_SECONDS):
            try:
                publish()
            except OSError:
                # The exclusive lock below still keeps sessions from opening once the lease has lapsed.
                pass

    descriptor = -1
    renewer = threading.Thread(target=renew, daemon=True)
    try:
        publish()
        renewer.start()
        descriptor = os.open(user_data / ACCESS_LOCK,
                             os.O_RDWR | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
        deadline = time.monotonic() + QUIESCE_BUDGET
        while True:
            try:
                fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except BlockingIOError:
                if time.monotonic() >= deadline:
                    raise HostsBusy from None
                time.sleep(0.05)
        yield
    finally:
        stop.set()
        if renewer.is_alive():
            renewer.join()
        # Release the lock before the lease, as the settings window does, so a session reopening on the lease going away can take its shared lock.
        if descriptor >= 0:
            os.close(descriptor)
        with contextlib.suppress(FileNotFoundError):
            lease.unlink()


def run_refresh(prefix: Path, options_file: Path, document: dict, resources: Path) -> tuple[subprocess.CompletedProcess, bool]:
    """msime-linux-prepare --refresh, pointed at resources. Returns the result and whether runtime-options.json was rewritten.

    A new resource directory is written into a copy of the options beside the file, and the copy replaces the file only once the refresh has rewritten it; on any failure the file never names the new directory."""
    command = str(prepare_executable(prefix))
    if Path(document["resources"]) == resources:
        result = subprocess.run([command, "--refresh", str(options_file)], capture_output=True, text=True, check=False)
        return result, result.returncode == 0 and result.stdout.strip() == "refreshed"
    # 保留文档约定的 runtime-options.json 文件名。刷新入口也会独立随安装包发布，不能因为副本是临时的就让它接受任意隐藏文件名。
    staged_directory = Path(tempfile.mkdtemp(prefix=".runtime-options-update-", dir=options_file.parent))
    staged = staged_directory / "runtime-options.json"
    try:
        with staged.open("w") as handle:
            json.dump(dict(document, resources=str(resources)), handle, indent=2, ensure_ascii=False)
            handle.write("\n")
        staged.chmod(options_file.stat().st_mode & 0o777)
        result = subprocess.run([command, "--refresh", str(staged)], capture_output=True, text=True, check=False)
        refreshed = result.returncode == 0 and result.stdout.strip() == "refreshed"
        if refreshed:
            staged.replace(options_file)
        return result, refreshed
    finally:
        shutil.rmtree(staged_directory, ignore_errors=True)


def update_dictionaries(prefix: Path, lock: dict, options_file: Path, download: bool) -> int:
    """把已有状态记录的那份词库补到已安装的锁，再切换代次并回放用户词库。"""
    document = read_options(options_file)
    resources = recorded_path(document, "resources", options_file)
    user_data = recorded_path(document, "user_data", options_file)
    if options_file.is_symlink():
        print(f"{options_file} 是符号链接，不是 msime-linux-prepare 生成的布局，不改写。", file=sys.stderr)
        return 1
    if not updatable(resources, prefix):
        print(
            f"词库目录 {resources} 不是当前用户自己下载的那份：随安装包提供的词库由包管理器更新，升级安装包后输入法会自己切换到新词库。",
            file=sys.stderr,
        )
        return 1
    problems = verify_directory(resources, lock)
    if problems and not download:
        print_problems(f"词库与当前版本不符：{resources}", problems)
        print("\n加 --download 按锁文件只取回缺失或不符的几项。", file=sys.stderr)
        return 1
    target = resources
    if problems:
        try:
            target = staged_resources(resources, lock)
        except OSError as error:
            raise SystemExit(f"无法建立新词库目录：{error}\n词库目录未改动：{resources}")
        remaining = fetch_missing(lock, target, resources)
        if remaining:
            print_problems("下载后仍不完整：", remaining)
            return 1
    print(f"词库已校验：{target}")
    try:
        with hosts_held_off(user_data):
            install_helpcodes(prefix, target)
            result, refreshed = run_refresh(prefix, options_file, document, target)
            if refreshed and running("ibus-daemon"):
                time.sleep(IBUS_OPTIONS_RELOAD)
    except HostsBusy:
        print("输入法仍有输入会话占用词库，没有切换：runtime-options.json 未改动，输入法继续使用旧词库。请稍后再运行一次。", file=sys.stderr)
        return 1
    except OSError as error:
        print(f"切换词库失败：{error}\nruntime-options.json 未改动，输入法继续使用旧词库。", file=sys.stderr)
        return 1
    if refreshed:
        print("已切换到新版本的词库，用户词库已回放进去。输入法在切换期间暂停了输入会话，现在已恢复，新的输入即使用新词库。")
        if target != resources:
            print(f"旧词库目录 {resources} 保留未动，确认新词库正常后可以自行删除。")
        return 0
    if result.returncode == 0:
        print(f"{options_file} 未改写：它已指向当前版本的词库，或不是 msime-linux-prepare 生成的布局。")
        return 0
    if result.stderr.strip():
        print(result.stderr.strip(), file=sys.stderr)
    if result.returncode == REFRESH_OUTDATED:
        print(
            "输入法的宿主库与已安装的词库锁不是同一版本，请重新安装安装包。runtime-options.json 未改动，输入法继续使用旧词库。",
            file=sys.stderr,
        )
    elif target != resources:
        print(f"切换词库失败：runtime-options.json 未改动，输入法继续使用旧词库。新词库已备在 {target}，再运行一次本命令即可重试。", file=sys.stderr)
    else:
        print("切换词库失败：runtime-options.json 未改动，输入法继续使用旧词库，下次启动时会再试。", file=sys.stderr)
    return 1


def running(name: str) -> bool:
    # pgrep -x 比对的是进程名（comm）。经包装脚本启动的程序，进程名是被包装的那个文件：Nix 的 wrapProgram 执行 .ibus-daemon-wrapped，进程名截成 .ibus-daemon-wr，只有 argv[0]（包装脚本以 exec -a 保留的调用路径）还是 ibus-daemon。所以再按命令行的第一个词比对一次。
    def found(*arguments: str) -> bool:
        return subprocess.run(["pgrep", *arguments], capture_output=True).returncode == 0
    return found("-x", name) or found("-f", f"^([^ ]*/)?{re.escape(name)}( |$)")


def service_units(state: Path, config: Path) -> list[str]:
    """登录后应当常驻的用户服务，对应 Windows 上随服务进程一直在的在线、语音和剪贴板功能。

    在线和语音服务都按 socket 激活，首个请求才真正启动进程：在线服务没有私有配置也能提供云候选；语音 provider 没有 voice-provider.json 也能启动，本地识别不需要凭据，云端识别在用户写好配置后的下一次请求才生效。剪贴板监视器读的是默认位置的 runtime-options.json，状态目录另选位置时它找不到配置，不启用。监视器本身只在偏好里开启剪贴板历史时才采集。
    """
    units = ["msime-linux-online.socket", "msime-linux-voice.socket"]
    if state == config:
        units.append("msime-linux-clipboard.service")
    return units


def enable_services(units: list[str]) -> None:
    if shutil.which("systemctl") is None:
        print("没有 systemctl：在线和语音服务可用 msime-linux-provider-session online|voice 手动启动。")
        return
    result = subprocess.run(
        ["systemctl", "--user", "enable", "--now", *units], capture_output=True, text=True, check=False
    )
    if result.returncode == 0:
        print("已启用用户服务：" + "、".join(units))
    else:
        print("启用用户服务失败，可稍后手动执行：systemctl --user enable --now " + " ".join(units), file=sys.stderr)
        if result.stderr.strip():
            print("  " + result.stderr.strip().splitlines()[-1], file=sys.stderr)


def ensure_anonymous_account(prefix: Path) -> None:
    """Create the per-user translation account as part of installation setup.

    Registration is best effort: a missing network must not leave dictionaries or the
    input method unprepared. The online provider retries lazily before the first account
    translation if this installation-time request could not reach the service.
    """
    provider = prefix / "bin/msime-linux-online-provider"
    if not provider.is_file():
        return
    try:
        result = subprocess.run(
            [str(provider), "--ensure-anonymous-account"],
            capture_output=True,
            text=True,
            timeout=30,
            check=False,
        )
    except (OSError, subprocess.TimeoutExpired) as error:
        print(f"匿名水杉账号注册暂时未完成：{error}；下次需要候选翻译时会重试。", file=sys.stderr)
        return
    if result.returncode != 0:
        detail = result.stderr.strip().splitlines()
        suffix = f"：{detail[-1]}" if detail else ""
        print(f"匿名水杉账号注册暂时未完成{suffix}；下次需要候选翻译时会重试。", file=sys.stderr)
    else:
        print("已自动注册本机匿名水杉账号。")


# The theme-set hook ships with the settings launcher (data/omarchy/theme-set.in); Omarchy runs every file in its theme-set.d after switching theme, and skips a dangling link, so a removed installation leaves nothing that fails.
OMARCHY_HOOK = "share/msime-client/omarchy/theme-set"


def omarchy_hook_link() -> Path:
    return Path.home() / ".config/omarchy/hooks/theme-set.d/msime"


def omarchy_desktop() -> bool:
    """Omarchy (basecamp/omarchy) keeps the applied theme in ~/.local/state/omarchy/current/theme and its user configuration in ~/.config/omarchy."""
    home = Path.home()
    return (home / ".local/state/omarchy/current/theme").is_dir() and (home / ".config/omarchy").is_dir()


def our_omarchy_hook(link: Path) -> bool:
    return link.is_symlink() and os.readlink(link).endswith(OMARCHY_HOOK)


def link_omarchy_theme_hook(prefix: Path, options_file: Path) -> None:
    """On Omarchy, link the theme-set hook and write the `omarchy` candidate skin from the current theme once, so the skin is listed before the first theme switch. Best effort, like the account: nothing here stops the input method from working."""
    hook = prefix / OMARCHY_HOOK
    settings = prefix / "bin/msime-linux-settings"
    if not omarchy_desktop() or not hook.is_file() or not settings.is_file():
        return
    link = omarchy_hook_link()
    if (link.exists() or link.is_symlink()) and not our_omarchy_hook(link):
        print(f"{link} 已存在且不是水杉的钩子，没有改动它；Omarchy 皮肤不会随主题切换更新。", file=sys.stderr)
        return
    try:
        link.parent.mkdir(parents=True, exist_ok=True)
        if link.is_symlink():
            link.unlink()
        link.symlink_to(hook)
        result = subprocess.run(
            [str(settings), "--sync-omarchy-theme"],
            env={**os.environ, "MSIME_CLIENT_HOST_OPTIONS": str(options_file)},
            capture_output=True,
            text=True,
            timeout=30,
            check=False,
        )
    except (OSError, subprocess.TimeoutExpired) as error:
        print(f"未能接入 Omarchy 主题：{error}", file=sys.stderr)
        return
    if result.returncode != 0:
        detail = result.stderr.strip().splitlines()
        suffix = f"：{detail[-1]}" if detail else ""
        print(f"已接入 Omarchy 主题钩子，但这次没能生成 Omarchy 皮肤{suffix}；下次切换 Omarchy 主题时会再生成。", file=sys.stderr)
        return
    print("已接入 Omarchy 主题：在输入法的「主题」菜单里选「Omarchy」，候选窗口就随 Omarchy 主题切换配色。")


def unlink_omarchy_theme_hook() -> str | None:
    link = omarchy_hook_link()
    if not our_omarchy_hook(link):
        return None
    link.unlink()
    return f"已移除 Omarchy 主题钩子 {link}"


# The bar widget (data/omarchy/plugin) replaces the tray Omarchy disables. Omarchy discovers user plugins with `find -L`, so a link to the installed folder is a plugin like any other, and `omarchy plugin remove` knows to only unlink it.
OMARCHY_PLUGIN = "share/msime-client/omarchy/plugin"
OMARCHY_PLUGIN_ID = "metasequoia.msime"


def omarchy_plugin_link() -> Path:
    return Path.home() / ".config/omarchy/plugins" / OMARCHY_PLUGIN_ID


def our_omarchy_plugin(link: Path) -> bool:
    return link.is_symlink() and os.readlink(link).endswith(OMARCHY_PLUGIN)


def link_omarchy_plugin(prefix: Path) -> None:
    """On Omarchy, link the bar widget into the user's plugins. Placing it on the bar is left to the user, as Omarchy leaves it for any plugin: setup does not rewrite their bar layout."""
    plugin = prefix / OMARCHY_PLUGIN
    if not omarchy_desktop() or not (plugin / "manifest.json").is_file():
        return
    link = omarchy_plugin_link()
    if (link.exists() or link.is_symlink()) and not our_omarchy_plugin(link):
        print(f"{link} 已存在且不是水杉的插件，没有改动它。", file=sys.stderr)
        return
    try:
        link.parent.mkdir(parents=True, exist_ok=True)
        if link.is_symlink():
            link.unlink()
        link.symlink_to(plugin)
    except OSError as error:
        print(f"未能接入 Omarchy 状态栏插件：{error}", file=sys.stderr)
        return
    print(f"已接入 Omarchy 状态栏插件：运行 `omarchy plugin enable {OMARCHY_PLUGIN_ID}` 把中/英和方案显示到状态栏，点它打开水杉菜单。")


def unlink_omarchy_plugin() -> str | None:
    link = omarchy_plugin_link()
    if not our_omarchy_plugin(link):
        return None
    link.unlink()
    return f"已移除 Omarchy 状态栏插件 {link}；状态栏里的位置可用 `omarchy plugin disable {OMARCHY_PLUGIN_ID}` 移除"


class RegistrationFailed(Exception):
    """One step of adding the input method to, or removing it from, the host's list did not work; setup falls back to printing the manual steps, and --unregister reports it and goes on with the other lists."""


def command_output(arguments: list[str]) -> str:
    try:
        result = subprocess.run(arguments, capture_output=True, text=True, timeout=COMMAND_TIMEOUT, check=False)
    except (OSError, subprocess.TimeoutExpired) as error:
        raise RegistrationFailed(f"无法执行 {arguments[0]}") from error
    if result.returncode != 0:
        detail = result.stderr.strip().splitlines()
        raise RegistrationFailed(f"{' '.join(arguments[:2])} 失败" + (f"：{detail[-1]}" if detail else ""))
    return result.stdout


# A quoted string, kept verbatim; a GVariant type annotation such as the `@a(ss)` gdbus and gsettings print before an empty array, dropped; or a GVariant boolean, spelled the Python way.
GVARIANT_TOKEN = re.compile(r"""('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|@[a-z(){}]+\s*|\b(true|false)\b""")
GVARIANT_BOOLEANS = {"true": "True", "false": "False"}


def parse_gvariant(text: str):
    """The GVariant text gdbus and gsettings print, for the shapes read here: strings, booleans and tuples and arrays of them. Those are Python literals once the type annotations are gone and the booleans are capitalised."""
    try:
        return ast.literal_eval(GVARIANT_TOKEN.sub(
            lambda match: match.group(1) or GVARIANT_BOOLEANS.get(match.group(2), ""), text.strip()
        ))
    except (ValueError, SyntaxError) as error:
        raise RegistrationFailed("无法解析返回值：" + text.strip()[:80]) from error


def gvariant_text(value) -> str:
    """The inverse of parse_gvariant for strings, booleans, tuples and non-empty arrays, the only values written here."""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, str):
        return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
    if isinstance(value, tuple):
        return "(" + ", ".join(gvariant_text(item) for item in value) + ("," if len(value) == 1 else "") + ")"
    return "[" + ", ".join(gvariant_text(item) for item in value) + "]"


def fcitx5_call(method: str, *arguments: str) -> str:
    return command_output([*FCITX5_CONTROLLER, f"{FCITX5_INTERFACE}.{method}", *arguments])


def fcitx5_group(name: str) -> tuple[str, list]:
    """The group's default layout and its (input method, layout) entries."""
    value = parse_gvariant(fcitx5_call("InputMethodGroupInfo", gvariant_text(name)))
    if not (
        isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], str) and isinstance(value[1], list)
        and all(isinstance(item, tuple) and len(item) == 2 and all(isinstance(part, str) for part in item)
                for item in value[1])
    ):
        raise RegistrationFailed("Fcitx5 返回的输入法组格式不符")
    return value


def fcitx5_current_group() -> str:
    current = parse_gvariant(fcitx5_call("CurrentInputMethodGroup"))
    group = current[0] if isinstance(current, tuple) and current else ""
    if not isinstance(group, str) or not group:
        raise RegistrationFailed("Fcitx5 没有返回当前输入法组")
    return group


def fcitx5_loaded() -> bool:
    # AvailableInputMethods returns one (unique name, name, native name, icon, label, language, configurable) entry per input method Fcitx5 has loaded.
    value = parse_gvariant(fcitx5_call("AvailableInputMethods"))
    entries = value[0] if isinstance(value, tuple) and value and isinstance(value[0], list) else []
    return any(isinstance(entry, tuple) and entry[:1] == (FCITX5_INPUT_METHOD,) for entry in entries)


def register_fcitx5() -> str:
    """Make Fcitx5 load the input method, then append it to Fcitx5's current group the way fcitx5-configtool would. Returns what happened, for the summary line."""
    if not fcitx5_loaded():
        # Fcitx5 loads addons when it starts, so an input method installed after it started is unknown until a restart, and SetInputMethodGroupInfo would drop the entry. The new instance takes a moment to come up.
        fcitx5_call("Restart")
        for _ in range(20):
            time.sleep(0.25)
            try:
                if fcitx5_loaded():
                    break
            except RegistrationFailed:
                pass
        else:
            raise RegistrationFailed(f"Fcitx5 重启之后仍没有加载 {FCITX5_INPUT_METHOD}")
    group = fcitx5_current_group()
    layout, items = fcitx5_group(group)
    if any(item[0] == FCITX5_INPUT_METHOD for item in items):
        return f"「{FCITX5_NAME}」已在 Fcitx5 当前输入法组「{group}」中。"
    if not items:
        # The first entry of a group is the input method Fcitx5 falls back to when inactive, which should be a keyboard layout; a group holding only this input method would leave nothing to switch back to.
        raise RegistrationFailed(f"Fcitx5 当前输入法组「{group}」为空，自动添加会让它没有可切回的键盘布局")
    fcitx5_call(
        "SetInputMethodGroupInfo", gvariant_text(group), gvariant_text(layout),
        gvariant_text([*items, (FCITX5_INPUT_METHOD, "")]),
    )
    # Fcitx5 drops entries naming an input method it has not loaded. Read the group back rather than report an addition that did not happen.
    _, items = fcitx5_group(group)
    if not any(item[0] == FCITX5_INPUT_METHOD for item in items):
        raise RegistrationFailed("Fcitx5 没有保存加入的水杉输入法")
    return f"已把「{FCITX5_NAME}」加入 Fcitx5 当前输入法组「{group}」，用 Fcitx5 的输入法切换快捷键即可切换到它。"


def ibus_lists_engine() -> bool:
    # `ibus list-engine` prints one "  <name> - <longname>" line per engine under each language heading.
    return any(line.split()[:1] == [IBUS_ENGINE] for line in command_output(["ibus", "list-engine"]).splitlines())


def gnome_desktop() -> bool:
    return "GNOME" in os.environ.get("XDG_CURRENT_DESKTOP", "").split(":")


def ibus_input_list() -> tuple[str, str, object]:
    """Where this desktop keeps the IBus engines it offers: GNOME Shell reads its own input sources and ignores IBus's preload list, every other IBus panel reads the preload list."""
    schemas = set(command_output(["gsettings", "list-schemas"]).split())
    if gnome_desktop() and GNOME_SOURCES[0] in schemas:
        return (*GNOME_SOURCES, ("ibus", IBUS_ENGINE))
    if IBUS_PRELOAD[0] in schemas:
        return (*IBUS_PRELOAD, IBUS_ENGINE)
    raise RegistrationFailed(f"没有 {IBUS_PRELOAD[0]} 设置项")


def register_ibus() -> str:
    """Make ibus-daemon know the engine, then append it to the desktop's input source list."""
    if not ibus_lists_engine():
        # ibus-daemon reads the component files when it starts, so an engine installed after it started is unknown until a restart. The new daemon takes a moment to come up.
        command_output(["ibus", "restart"])
        for _ in range(20):
            time.sleep(0.25)
            try:
                if ibus_lists_engine():
                    break
            except RegistrationFailed:
                pass
        else:
            raise RegistrationFailed(f"ibus restart 之后 IBus 仍没有列出 {IBUS_ENGINE}")
    schema, key, entry = ibus_input_list()
    current = parse_gvariant(command_output(["gsettings", "get", schema, key]))
    if not isinstance(current, list):
        raise RegistrationFailed(f"{schema} {key} 不是列表")
    if entry in current:
        return f"「{IBUS_NAME}」已在输入源列表中。"
    if not current:
        # An empty list means the desktop is falling back to a default it does not store here; writing a list with only this engine would take that default layout away.
        raise RegistrationFailed(f"{schema} {key} 为空，桌面正在使用未写入该项的默认输入源，自动添加会把它替换掉")
    command_output(["gsettings", "set", schema, key, gvariant_text([*current, entry])])
    return f"已把「{IBUS_NAME}」加入输入源列表，用桌面的输入法切换快捷键即可切换到它。"


def fcitx5_on_bus() -> bool:
    """Whether Fcitx5 owns its name on this session bus. Asked of the bus itself, so a Fcitx5 that is not running is never D-Bus activated just to be edited, and one running in another user's session does not count."""
    owner = parse_gvariant(command_output([
        "gdbus", "call", "--session", "--dest", "org.freedesktop.DBus", "--object-path", "/org/freedesktop/DBus",
        "--method", "org.freedesktop.DBus.NameHasOwner", gvariant_text(FCITX5_BUS_NAME),
    ]))
    return owner == (True,)


def unregister_fcitx5() -> str:
    """The inverse of register_fcitx5: drop the input method from Fcitx5's current group. Returns what happened."""
    if not fcitx5_on_bus():
        return "Fcitx5 没有在运行，其输入法组未改动。"
    group = fcitx5_current_group()
    layout, items = fcitx5_group(group)
    remaining = [item for item in items if item[0] != FCITX5_INPUT_METHOD]
    if len(remaining) == len(items):
        return f"「{FCITX5_NAME}」不在 Fcitx5 当前输入法组「{group}」中。"
    if not remaining:
        # Same rule as registering: an empty group leaves Fcitx5 nothing to fall back to when inactive, so a group holding only this input method is left for the user to fix.
        return f"Fcitx5 当前输入法组「{group}」只有「{FCITX5_NAME}」，移除后会变空，保持不变。"
    fcitx5_call("SetInputMethodGroupInfo", gvariant_text(group), gvariant_text(layout), gvariant_text(remaining))
    return f"已从 Fcitx5 当前输入法组「{group}」移除「{FCITX5_NAME}」。"


def unregister_setting(schema: str, key: str, entry) -> str:
    """The inverse of register_ibus for one list. Returns what happened."""
    current = parse_gvariant(command_output(["gsettings", "get", schema, key]))
    if not isinstance(current, list):
        raise RegistrationFailed(f"{schema} {key} 不是列表")
    remaining = [item for item in current if item != entry]
    if len(remaining) == len(current):
        return f"「{IBUS_NAME}」不在 {schema} {key} 中。"
    if not remaining:
        # An empty list hands the desktop back to a default it does not store here, which may not be what the user had before; leave the list for the user to change.
        return f"{schema} {key} 只有「{IBUS_NAME}」，移除后会变空，保持不变。"
    command_output(["gsettings", "set", schema, key, gvariant_text(remaining)])
    return f"已从 {schema} {key} 移除「{IBUS_NAME}」。"


def xdg_base(variable: str, fallback: str) -> Path:
    """An XDG base directory as the hosts resolve it: a relative value is ignored, as the specification requires."""
    value = os.environ.get(variable)
    return Path(value) if value and Path(value).is_absolute() else Path.home() / fallback


def fcitx5_unescape(value: str) -> str:
    """A value as Fcitx5's INI reader returns it: a quoted value loses its quotes and its escaped quotes, and backslash escapes are resolved in either form."""
    quoted = len(value) >= 2 and value[0] == value[-1] == '"'
    if quoted:
        value = value[1:-1]
    return re.sub(r"\\(.)", lambda match: "\n" if match.group(1) == "n" else match.group(1), value)


def fcitx5_escape(value: str) -> str:
    """The inverse, as Fcitx5 writes it: a value holding whitespace or a quote is quoted."""
    escaped = value.replace("\\", "\\\\").replace("\n", "\\n")
    if not any(character.isspace() or character == '"' for character in value):
        return escaped
    return '"' + escaped.replace('"', '\\"') + '"'


def classicui_file() -> Path:
    return config_home() / "fcitx5/conf/classicui.conf"


def classicui_options(path: Path) -> dict[str, str]:
    """The top-level options of classicui.conf, which is where Fcitx5 saves every change to the addon's configuration, whether MSIME, fcitx5-configtool or anything else made it."""
    options = {}
    with contextlib.suppress(FileNotFoundError):
        for line in path.read_text().splitlines():
            line = line.strip()
            if line.startswith("["):
                break
            if line and not line.startswith("#") and "=" in line:
                key, value = line.split("=", 1)
                options[key.strip()] = fcitx5_unescape(value.strip())
    return options


def edit_classicui(path: Path, values: dict[str, str]) -> None:
    """Set top-level options in classicui.conf in place, for a Fcitx5 that is not running; the other lines, comments and sections stay as they were. Only options the file holds are restored, since only those can hold what MSIME wrote."""
    lines = path.read_text().splitlines()
    for index, line in enumerate(lines):
        stripped = line.strip()
        if stripped.startswith("["):
            break
        key = stripped.split("=", 1)[0].strip()
        if "=" in stripped and not stripped.startswith("#") and key in values:
            lines[index] = f"{key}={fcitx5_escape(values[key])}"
    staged = path.with_name(path.name + ".msime-new")
    staged.write_text("".join(line + "\n" for line in lines))
    os.replace(staged, path)


def fcitx5_config_variant(values: dict[str, str]) -> str:
    """SetConfig's argument: a variant holding the a{sv} map Fcitx5 turns back into the addon's raw configuration."""
    return "<{" + ", ".join(f"{gvariant_text(key)}: <{gvariant_text(value)}>" for key, value in values.items()) + "}>"


def restorable(entries: dict, current) -> tuple[dict, list[str]]:
    """Split a host's record into the values to put back, for settings that still hold what MSIME wrote, and the names of those the user has changed since."""
    restore, kept = {}, []
    for key, entry in entries.items():
        if isinstance(entry, dict) and "prior" in entry and "written" in entry and current(key) == entry["written"]:
            restore[key] = entry["prior"]
        else:
            kept.append(key)
    return restore, kept


def kept_note(kept: list[str]) -> str:
    return f"；{'、'.join(kept)} 在水杉写入之后已被改动，保持不变" if kept else ""


def restore_fcitx5_panel(entries: dict) -> str | None:
    """Put back the classicui options MSIME replaced. A running Fcitx5 takes them over D-Bus, the way fcitx5-configtool writes them, so it applies and saves them itself; otherwise classicui.conf is edited, since a file edited under a running Fcitx5 is overwritten by its next save."""
    path = classicui_file()
    current = classicui_options(path)
    restore, kept = restorable(entries, current.get)
    # A value never read from the addon cannot be put back.
    restore = {key: value for key, value in restore.items() if isinstance(value, str)}
    # MSIME's theme is removed after this, so a theme option left naming it goes back to the stock theme: one set by a build that kept no record, or recorded by it as the value it replaced.
    for key, stock in FCITX5_STOCK_THEMES.items():
        if restore.get(key, current.get(key)) == FCITX5_THEME:
            restore[key] = stock
            if key in kept:
                kept.remove(key)
    if not restore:
        return "Fcitx5 候选面板设置无需恢复" + kept_note(kept) + "。" if entries else None
    names = "、".join(restore)
    try:
        if fcitx5_on_bus():
            fcitx5_call("SetConfig", gvariant_text(FCITX5_CLASSICUI_URI), fcitx5_config_variant(restore))
            return f"已恢复 Fcitx5 候选面板设置 {names}" + kept_note(kept) + "。"
    except RegistrationFailed as error:
        print(f"未能经 D-Bus 恢复 Fcitx5 候选面板设置：{error}，改为直接编辑 {path}", file=sys.stderr)
    try:
        edit_classicui(path, restore)
    except OSError as error:
        raise RegistrationFailed(f"无法写入 {path}：{error.strerror}") from error
    return f"已在 {path} 恢复 Fcitx5 候选面板设置 {names}" + kept_note(kept) + "。"


def restore_ibus_panel(entries: dict) -> str | None:
    """Put back the IBus panel font keys MSIME replaced; a key the user had never set is reset to the schema default."""
    if not entries:
        return None
    if IBUS_PANEL not in set(command_output(["gsettings", "list-schemas"]).split()):
        return f"没有 {IBUS_PANEL} 设置项，IBus 候选面板设置无需恢复。"
    restore, kept = restorable(
        entries, lambda key: parse_gvariant(command_output(["gsettings", "get", IBUS_PANEL, key]))
    )
    # The hosts record strings, booleans and null; anything else did not come from them.
    kept += [key for key, value in restore.items() if not isinstance(value, (str, bool, type(None)))]
    restore = {key: value for key, value in restore.items() if key not in kept}
    for key, value in restore.items():
        if value is None:
            command_output(["gsettings", "reset", IBUS_PANEL, key])
        else:
            command_output(["gsettings", "set", IBUS_PANEL, key, gvariant_text(value)])
    if not restore:
        return "IBus 候选面板设置无需恢复" + kept_note(kept) + "。"
    return f"已恢复 IBus 候选面板设置 {'、'.join(restore)}" + kept_note(kept) + "。"


@contextlib.contextmanager
def panel_restore_lock(record_file: Path):
    """The lock the hosts hold around each change to the record (src/candidates/PanelRestoreRecord.h). Its file is never removed: a host waiting on the old one while another opened a new one would put both in the critical section at once."""
    descriptor = os.open(record_file.with_name(record_file.name + ".lock"),
                         os.O_RDWR | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
    try:
        fcntl.flock(descriptor, fcntl.LOCK_EX)
        yield
    finally:
        os.close(descriptor)


def read_bounded_text(path: Path, limit: int) -> str:
    flags = os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW
    with os.fdopen(os.open(path, flags), "rb") as source:
        raw = source.read(limit + 1)
    if len(raw) > limit:
        raise ValueError(f"文件超过 {limit} 字节限制")
    return raw.decode()


def restore_panel_settings() -> None:
    """Undo what the hosts changed in the desktop's candidate panel settings, which every input method shares, and remove the theme MSIME generated for Fcitx5. The record is removed once every host's settings were dealt with; a failure keeps it, so a later --unregister can still restore them.

    The hosts replace the record atomically, so it is read without the lock. The lock is not held while restoring either: a running Fcitx5 applies the options on the thread its host would be waiting on the lock from. Instead the record is removed under the lock only if it is still the one read, so a change a host still running recorded meanwhile is kept for a later --unregister."""
    record_file = xdg_base("XDG_STATE_HOME", ".local/state") / PANEL_RESTORE_FILE
    text = None
    try:
        text = read_bounded_text(record_file, PANEL_RESTORE_LIMIT)
        record = json.loads(text)
    except FileNotFoundError:
        record = {}
    except (OSError, ValueError) as error:
        print(f"无法读取候选面板设置的恢复记录 {record_file}：{error}", file=sys.stderr)
        record = None
    complete = record is not None
    for host, restore in (("fcitx5", restore_fcitx5_panel), ("ibus", restore_ibus_panel)):
        entries = record.get(host) if isinstance(record, dict) else None
        try:
            # The Fcitx5 theme options are looked at even without a record: builds before it set MSIME's theme without one.
            message = restore(entries if isinstance(entries, dict) else {})
        except RegistrationFailed as error:
            complete = False
            print(f"未能恢复候选面板设置：{error}", file=sys.stderr)
        else:
            if message:
                print(message)
    theme = xdg_base("XDG_DATA_HOME", ".local/share") / "fcitx5/themes" / FCITX5_THEME
    if theme.is_dir():
        try:
            shutil.rmtree(theme)
            print(f"已删除水杉生成的 Fcitx5 主题 {theme}。")
        except OSError as error:
            print(f"未能删除水杉生成的 Fcitx5 主题 {theme}：{error.strerror}", file=sys.stderr)
    if text is None:
        return
    if complete:
        try:
            with panel_restore_lock(record_file):
                if read_bounded_text(record_file, PANEL_RESTORE_LIMIT) == text:
                    record_file.unlink()
                    return
        except FileNotFoundError:
            return
        except (OSError, ValueError) as error:
            detail = getattr(error, "strerror", None) or str(error)
            print(f"未能删除候选面板设置的恢复记录 {record_file}：{detail}", file=sys.stderr)
            return
        print(f"恢复期间宿主又记下了候选面板设置的改动，恢复记录保留在 {record_file}，可稍后再次运行 msime-linux-setup --unregister。", file=sys.stderr)
    elif record is not None:
        print(f"恢复记录保留在 {record_file}，可稍后再次运行 msime-linux-setup --unregister。", file=sys.stderr)


def use_runtime_session_bus() -> None:
    runtime = os.environ.get("XDG_RUNTIME_DIR")
    if not os.environ.get("DBUS_SESSION_BUS_ADDRESS") and runtime and (Path(runtime) / "bus").exists():
        # A transient unit in the user's systemd manager inherits only what the desktop imported into it; without the session bus address gsettings would write to a throwaway backend and gdbus would find no bus. The user bus of systemd sessions lives at this path.
        os.environ["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={Path(runtime) / 'bus'}"


def unregister_input_method() -> None:
    """Remove the input method from every list setup may have added it to, one list at a time so a missing tool or bus only skips its own list.

    Unlike registering, this does not depend on which host is running or on the desktop: the uninstaller runs it from the user's systemd manager, where XDG_CURRENT_DESKTOP is often unset, and a list can hold the entry from an earlier session under another desktop. Both IBus lists are cleaned whenever their schema is installed.
    """
    use_runtime_session_bus()
    steps = [unregister_fcitx5]
    try:
        schemas = set(command_output(["gsettings", "list-schemas"]).split())
    except RegistrationFailed as error:
        print(f"未能读取输入源设置：{error}", file=sys.stderr)
        schemas = set()
    for schema, key, entry in ((*GNOME_SOURCES, ("ibus", IBUS_ENGINE)), (*IBUS_PRELOAD, IBUS_ENGINE)):
        if schema in schemas:
            steps.append(lambda schema=schema, key=key, entry=entry: unregister_setting(schema, key, entry))
    for step in steps:
        try:
            print(step())
        except RegistrationFailed as error:
            print(f"未能从输入法列表移除：{error}", file=sys.stderr)
    for removed in (unlink_omarchy_theme_hook(), unlink_omarchy_plugin()):
        if removed:
            print(removed)
    restore_panel_settings()


def register_again() -> int:
    """已完成首次配置的用户：重新启用用户服务、链回 Omarchy 的钩子和插件，并把输入法加回正在运行的宿主的输入法列表，即撤销 --unregister 和卸载时停用单元的那两步。

    发行版仓库里的 msime 包替换发布页的 msime-linux 包（或 AUR 的 msime 与 msime-bin 互换）时，被替换的包按卸载处理，它的卸载脚本对每个用户停用单元并运行 --unregister，而文件仍由新包提供；新包装好之后以临时单元替每个用户运行这里。只看默认位置的状态目录（剪贴板监视器和首次配置引导读的也是它）；没有 runtime-options.json 说明这个用户没配置过，什么也不做。不检查、不下载词库，也不改状态目录里的任何文件。
    """
    use_runtime_session_bus()
    state = config_home() / "msime-client"
    options_file = state / "runtime-options.json"
    if not options_file.is_file():
        print(f"{state} 里没有 runtime-options.json，还没有完成首次配置，没有要恢复的。")
        return 0
    prefix = install_prefix()
    enable_services(service_units(state, state))
    link_omarchy_theme_hook(prefix, options_file)
    link_omarchy_plugin(prefix)
    host = active_host()
    registered = register_input_method(host)
    if registered:
        print(registered)
    elif host == "fcitx5":
        print(f"下一步：用 fcitx5-configtool 把「{FCITX5_NAME}」（英文界面显示为「MSIME」）加入当前输入法组。")
    elif host == "ibus":
        print(f"下一步：ibus restart，再在输入源里添加「{IBUS_NAME}」。")
    else:
        print("Fcitx5 和 IBus 都没有在运行，输入法列表没有改动；启动其中一个后再运行 msime-linux-setup --register。")
    print_gnome_wayland_gtk_note(host)
    print_linglong_ibus_note(host)
    return 0


def active_host() -> str | None:
    if running("fcitx5"):
        return "fcitx5"
    if running("ibus-daemon"):
        return "ibus"
    return None


# GNOME 的 Wayland 会话不让输入法自己弹出候选窗。GTK 程序设了 GTK_IM_MODULE=fcitx 时，候选窗由程序里的 fcitx5-gtk 客户端面板绘制，它在 GTK3 上移动弹窗必须先隐藏再显示，于是不停闪烁，也不用水杉的 Fcitx5 主题；不设时 GTK 走 text-input → GNOME Shell → Fcitx5 的 IBus 前端，候选窗由 Fcitx5 经典界面按水杉主题绘制。见 README「GNOME Wayland 下候选窗闪烁」。
GNOME_WAYLAND_GTK_NOTE = (
    "提示：当前是 GNOME 的 Wayland 会话，且设置了 GTK_IM_MODULE=fcitx。这时 GTK 程序的候选窗由程序自己绘制，"
    "会不停闪烁，也不显示水杉的候选窗皮肤。GNOME Wayland 下不要为 GTK 设置 GTK_IM_MODULE，"
    "做法见 platforms/linux/README.md 的「GNOME Wayland 下候选窗闪烁」一节"
    "（https://github.com/metasequoiaime/msime/blob/develop/platforms/linux/README.md），改完重新登录。"
)


def gnome_wayland_gtk_note(host: str | None, environment: dict[str, str], manager: dict[str, str]) -> str | None:
    """输入法注册进 Fcitx5、会话是 GNOME 的 Wayland、GTK 程序会加载 fcitx 输入法模块时，返回要打印的提示，否则 None。

    `environment` 是本进程的环境，`manager` 是用户级 systemd 的环境（`systemctl --user show-environment`）。会话类型和桌面以本进程为准，取不到时（安装包以临时单元运行本命令）看 systemd 的。GTK_IM_MODULE 两处任何一处是 fcitx 都提示：从桌面启动的程序继承登录环境，D-Bus 激活的程序（例如 gnome-terminal）继承 systemd 的，开了 Linger 时后者会留着上次会话的值。只提示，不改用户的文件。
    """
    if host != "fcitx5":
        return None
    def value(name: str) -> str:
        return environment.get(name) or manager.get(name, "")
    if value("XDG_SESSION_TYPE") != "wayland" or "GNOME" not in value("XDG_CURRENT_DESKTOP").split(":"):
        return None
    if "fcitx" not in (environment.get("GTK_IM_MODULE"), manager.get("GTK_IM_MODULE")):
        return None
    return GNOME_WAYLAND_GTK_NOTE


def user_manager_environment() -> dict[str, str]:
    """用户级 systemd 的环境；没有 systemctl 或读不到时为空。"""
    if shutil.which("systemctl") is None:
        return {}
    try:
        result = subprocess.run(["systemctl", "--user", "show-environment"], capture_output=True, text=True,
                                timeout=COMMAND_TIMEOUT, check=False)
    except (OSError, subprocess.TimeoutExpired):
        return {}
    if result.returncode != 0:
        return {}
    pairs = (line.partition("=") for line in result.stdout.splitlines())
    return {name: value for name, separator, value in pairs if separator}


def print_gnome_wayland_gtk_note(host: str | None) -> None:
    if host != "fcitx5":
        return
    environment = dict(os.environ)
    # 本进程的环境已经能下结论时不去问 systemd：不是 GNOME Wayland，或者本进程自己就设了 fcitx。
    session = environment.get("XDG_SESSION_TYPE")
    desktop = environment.get("XDG_CURRENT_DESKTOP")
    if session and desktop and gnome_wayland_gtk_note(host, environment, {"GTK_IM_MODULE": "fcitx"}) is None:
        return
    manager = {} if gnome_wayland_gtk_note(host, environment, {}) else user_manager_environment()
    note = gnome_wayland_gtk_note(host, environment, manager)
    if note:
        print(note)


# 注册到 IBus daemon 且玲珑运行时缺少 IBus 模块时，改用 Fcitx5 是可选排查路径；仅凭发行版和环境变量不能认定模块缺失。Fcitx5 自身也可接收 IBus 前端连接（#8009），见 README「deepin 玲珑应用里只能输入字母」。
LINGLONG_IBUS_NOTE = (
    "提示：这台机器上有玲珑（Linglong）应用环境，而水杉输入法注册在 IBus 里。若玲珑应用只能输入字母，"
    "请先确认应用运行时是否缺少 IBus 模块；GTK_IM_MODULE=ibus 也可能连接的是 Fcitx5 的 IBus 兼容前端。"
    "确认使用 IBus daemon 且缺少模块时，可以考虑改用 Fcitx5：im-config -n fcitx5，重新登录后运行 msime-linux-setup --register "
    "把水杉输入法加进 Fcitx5；已连接 Fcitx5 仍失败的情况需要继续排查。详细步骤见 platforms/linux/README.md 的「deepin 玲珑应用里只能输入字母」一节"
    "（https://github.com/metasequoiaime/msime/blob/develop/platforms/linux/README.md）。"
)

# 带玲珑的发行版：deepin（含 deepin 23/25）和统信 UOS 默认装着玲珑。
LINGLONG_DISTRIBUTIONS = {"deepin", "uos"}


OS_RELEASE_FILES = (Path("/etc/os-release"), Path("/usr/lib/os-release"))


def os_release(paths: tuple[Path, ...] = OS_RELEASE_FILES) -> dict[str, str]:
    """第一份读得到的 os-release（先 /etc，再 /usr/lib）的键值；都读不到时为空。"""
    for path in paths:
        try:
            text = path.read_text(encoding="utf-8", errors="replace")
        except OSError:
            continue
        pairs = (line.partition("=") for line in text.splitlines())
        return {name.strip(): value.strip().strip("\"'") for name, separator, value in pairs if separator}
    return {}


def linglong_installed() -> bool:
    """装了玲珑：有它的命令行 `ll-cli`，或者有它的数据目录。"""
    return shutil.which("ll-cli") is not None or Path("/var/lib/linglong").is_dir()


def fcitx5_addon_installed(prefix: Path) -> bool:
    """本安装带不带 Fcitx5 插件：插件条目 fcitx5/addon/<插件名>.conf 在不在。full 和自定义前缀的安装把它装在前缀的 share 下，装在 /opt 下的版本装在 /usr/share 下（fcitx5/CMakeLists.txt）。不带插件的构建（-DMSIME_ENABLE_FCITX5=OFF，例如 UOS 20、Debian 10 用的 legacy 包）没有这个文件。"""
    entry = Path("fcitx5/addon") / f"{FCITX5_INPUT_METHOD}.conf"
    return any((directory / entry).is_file() for directory in (prefix / "share", Path("/usr/share")))


def linglong_ibus_note(host: str | None, release: dict[str, str], linglong: bool, fcitx5_addon: bool) -> str | None:
    """输入法注册进 IBus、本安装带 Fcitx5 插件、且这台机器是 deepin/UOS 或装了玲珑时，返回要打印的提示，否则 None。只提示，不替用户切换框架。

    不带 Fcitx5 插件的安装不提示：提示让用户切到 Fcitx5 并把水杉注册进去，而那里没有水杉的插件，照做之后所有应用里都用不了水杉，不只是玲珑应用。
    """
    if host != "ibus" or not fcitx5_addon:
        return None
    distributions = {release.get("ID", "").lower(), *release.get("ID_LIKE", "").lower().split()}
    if not linglong and not distributions & LINGLONG_DISTRIBUTIONS:
        return None
    return LINGLONG_IBUS_NOTE


def print_linglong_ibus_note(host: str | None) -> None:
    if host != "ibus":
        return
    note = linglong_ibus_note(host, os_release(), linglong_installed(), fcitx5_addon_installed(install_prefix()))
    if note:
        print(note)


def register_input_method(host: str | None) -> str | None:
    """Add the input method to the running host's list. Returns the line to print, or None when the manual steps should be printed instead."""
    if host is None:
        return None
    try:
        return register_fcitx5() if host == "fcitx5" else register_ibus()
    except RegistrationFailed as error:
        print(f"未能自动加入输入法列表：{error}", file=sys.stderr)
        return None


def next_steps(state: Path, host: str | None, registered: str | None) -> None:
    print()
    print(f"状态目录已就绪：{state}")
    if registered:
        print(registered)
    elif host == "fcitx5":
        print(f"下一步：用 fcitx5-configtool 把「{FCITX5_NAME}」（英文界面显示为「MSIME」）加入当前输入法组。")
    elif host == "ibus":
        print(f"下一步：ibus restart，再在输入源里添加「{IBUS_NAME}」。")
    else:
        print("下一步：启动 fcitx5 或 ibus，再在各自的设置里加入水杉输入法。")
    if host == "fcitx5":
        print("  状态栏上的中英文、简繁、工具栏等入口挂在输入法状态区，需要桌面提供托盘")
        print("  宿主；若发行版以 fcitx5 --disable notificationitem 启动，这些入口不会显示，")
        print("  但输入本身不受影响，设置也可以从应用列表里的「水杉输入法」打开。")
    print_gnome_wayland_gtk_note(host)
    print_linglong_ibus_note(host)
    print("设置面板：msime-linux-settings（需要安装时提供了桌面二进制）")


# 各版本（full、拼音、五笔等）是各自独立的安装包，可以同时安装，每个包带着自己的这个脚本：它只配置、注销本版本，状态目录、词库、用户服务和输入法条目都是本版本自己的。IBUS_ENGINE 就是包名，full 是 msime-linux，其他版本是 msime-linux-<id>。
EDITION_PACKAGE_PREFIX = "msime-linux-"
EDITION_ID = re.compile(r"[a-z][a-z0-9]*")


def installed_edition() -> str:
    """本脚本所属安装包的版本 id。"""
    return IBUS_ENGINE[len(EDITION_PACKAGE_PREFIX):] if IBUS_ENGINE.startswith(EDITION_PACKAGE_PREFIX) else "full"


def edition_setup_program(edition: str) -> Path:
    """另一个版本的首次配置命令：它在 /usr/bin 下以那个版本的包名命名（full 是 msime-linux-setup，其他版本是指向 /opt/msime-linux-<id> 的 msime-linux-<id>-setup）。"""
    package = EDITION_PACKAGE_PREFIX.rstrip("-") if edition == "full" else EDITION_PACKAGE_PREFIX + edition
    return Path("/usr/bin") / f"{package}-setup"


def delegate_to_edition(edition: str, argv: list[str]) -> None:
    """--edition 指的不是本版本时，换成那个版本自己的命令来做，参数原样带过去；那个版本没装时报错，不拿本版本去配置它。"""
    if not EDITION_ID.fullmatch(edition):
        raise SystemExit(f"版本 id 只能是小写字母和数字：{edition}")
    program = edition_setup_program(edition)
    if not os.access(program, os.X_OK):
        raise SystemExit(f"没有安装 {edition} 版本：找不到 {program}")
    os.execv(program, [str(program), *argv])


def without_edition_argument(argv: list[str]) -> list[str]:
    """去掉命令行里的 --edition 及其值。"""
    remaining = []
    skip = False
    for argument in argv:
        if skip:
            skip = False
        elif argument == "--edition":
            skip = True
        elif not argument.startswith("--edition="):
            remaining.append(argument)
    return remaining


def main() -> int:
    parser = argparse.ArgumentParser(description="水杉输入法 Linux 首次配置")
    parser.add_argument(
        "--edition",
        help=f"要配置的版本（full、pinyin、wubi 等），默认是本命令所属的版本 {installed_edition()}；指定另一个版本时交给那个版本自己的首次配置命令",
    )
    parser.add_argument("--resources", type=Path, help="已备齐的词库目录（绝对路径）")
    parser.add_argument("--state", type=Path, help="要创建的状态目录，默认 $XDG_CONFIG_HOME/msime-client")
    parser.add_argument(
        "--download",
        action="store_true",
        help="允许按已安装的词库锁下载缺失词库（首次约 170 MB），默认不下载；状态目录已有 runtime-options.json 时即视为 --update",
    )
    parser.add_argument(
        "--update",
        action="store_true",
        help="升级之后把已有状态记录的词库补到当前版本并切换过去，用户词库随之回放；缺的词库要配合 --download 取回",
    )
    cloud = parser.add_mutually_exclusive_group()
    cloud.add_argument(
        "--cloud-candidates",
        action="store_true",
        help="启用云候选（默认关闭）：输入过程中把正在输入的拼写经 HTTPS 发给 Google input-tools（inputtools.google.com）换回一条额外候选；已上屏文本、词库和词频不会发送。之后可在设置里改",
    )
    cloud.add_argument(
        "--no-cloud-candidates",
        action="store_true",
        help="保持云候选关闭；现在默认就是关闭，保留给旧的调用方",
    )
    parser.add_argument(
        "--no-register",
        action="store_true",
        help="不把输入法加入正在运行的 Fcitx5 或 IBus 的输入法列表，只打印手动添加的步骤",
    )
    parser.add_argument(
        "--unregister",
        action="store_true",
        help="把水杉输入法从 GNOME 输入源、IBus 预载引擎和 Fcitx5 当前输入法组中移除，恢复被改过的候选面板主题、字体和滚轮翻页设置后退出，不准备状态也不下载；卸载时自动执行",
    )
    parser.add_argument(
        "--register",
        action="store_true",
        help="已完成首次配置时，重新启用在线、语音和剪贴板服务，并把水杉输入法加回正在运行的 Fcitx5 或 IBus 的输入法列表，不检查词库也不改状态；还没有配置过时什么也不做。发行版仓库的包替换掉另一个同样内容的包（例如 msime 替换发布页的 msime-linux）之后自动执行：被替换的包卸载时撤销了这两样",
    )
    arguments = parser.parse_args()
    if arguments.register and arguments.unregister:
        parser.error("--register 与 --unregister 不能同时使用")
    if arguments.edition and arguments.edition != installed_edition():
        delegate_to_edition(arguments.edition, without_edition_argument(sys.argv[1:]))
    if arguments.unregister:
        unregister_input_method()
        return 0
    if arguments.register:
        return register_again()

    prefix = install_prefix()
    state = (arguments.state or config_home() / "msime-client").expanduser()
    if not state.is_absolute():
        raise SystemExit("状态目录必须是绝对路径")
    options_file = state / "runtime-options.json"
    update = arguments.update or (arguments.download and options_file.is_file())
    if update and arguments.resources:
        raise SystemExit("--update 使用状态目录记录的词库目录，不能再用 --resources 另指一份。")
    if update and not options_file.is_file():
        raise SystemExit(f"{state} 里没有 runtime-options.json，还没有完成首次配置：去掉 --update 先做一次首次配置。")
    if state.exists() and not update and not anonymous_account_state(state):
        raise SystemExit(
            f"状态目录已存在：{state}\n"
            "msime-linux-prepare 不覆盖已有目录。要重新准备请另选目录，或先自行移走这一份。\n"
            "升级之后要把这份状态换到新版本的词库，运行 msime-linux-setup --update --download。"
        )

    lock_file = next((path for path in lock_candidates(prefix) if path.is_file()), None)
    if lock_file is None:
        raise SystemExit(
            "找不到 desktop-dictionary.lock.json。它随安装提供；"
            "自定义前缀可用 MSIME_DICTIONARY_LOCK 指向它。"
        )
    lock = json.loads(lock_file.read_text())
    if update:
        status = update_dictionaries(prefix, lock, options_file, arguments.download)
        link_omarchy_theme_hook(prefix, options_file)
        link_omarchy_plugin(prefix)
        return status

    if arguments.resources:
        resources = arguments.resources.expanduser()
        if not resources.is_absolute():
            raise SystemExit("词库目录必须是绝对路径")
    else:
        resources = next(
            (path for path in resource_candidates(prefix) if verify_directory(path, lock) == []),
            data_home() / "msime-client/resources",
        )

    problems = verify_directory(resources, lock)
    if problems and not arguments.download:
        print_problems(f"词库目录不可用：{resources}", problems)
        print(
            "\n加 --download 按锁文件取回（首次约 170 MB），"
            "或用 --resources 指向一份已备齐的目录。",
            file=sys.stderr,
        )
        return 1
    if problems:
        remaining = fetch_missing(lock, resources)
        if remaining:
            print_problems("下载后仍不完整：", remaining)
            return 1

    print(f"词库已校验：{resources}")
    try:
        install_helpcodes(prefix, resources)
    except OSError as error:
        raise SystemExit(f"准备辅助码失败：{error}") from error
    prepare_state(prefix, resources, state, arguments.cloud_candidates)
    ensure_anonymous_account(prefix)
    enable_services(service_units(state, config_home() / "msime-client"))
    link_omarchy_theme_hook(prefix, options_file)
    link_omarchy_plugin(prefix)
    host = active_host()
    next_steps(state, host, None if arguments.no_register else register_input_method(host))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
