#!/usr/bin/env python3
# summary: Back up your home folder and restore files.
"""starchaser backup: Settings > Backups. Copies your Home folder to an external drive, and brings files back.

  starchaser backup status          JSON: the drive, whether it is plugged in, the last backup, the space it uses,
                                    a backup or restore running now
  starchaser backup drives          JSON: the external drives plugged in now
  starchaser backup use UUID        back up to this drive from now on (JSON on stdin: {"encrypt": true|false,
                                    "password": "..."}). A drive that already has your backups is used as it is
                                    (its password, if it has one, is asked for); otherwise the backup folder is made
                                    there (asks for your password only when the drive's top folder is the computer's)
  starchaser backup set schedule hourly|daily|weekly
  starchaser backup set skip-vms on|off   leave out virtual machine disks (large files that change all the time)
  starchaser backup start           back up now, in the background
  starchaser backup stop-using      stop backing up to the drive (the backups on it stay)
  starchaser backup snapshots       JSON: the backups on the drive, newest first
  starchaser backup files ID [FOLDER]
                                    JSON: what one folder of backup ID holds (FOLDER relative to your Home folder)
  starchaser backup restore-start ID home|FOLDER [PATH ...]
                                    put files back from backup ID, in the background: home puts them where they
                                    were, FOLDER (an existing folder) puts them in a new folder inside it. PATHs
                                    (relative to your Home folder) pick files and folders; none means everything.
                                    --mode keep (default) keeps newer files; replace restores older copies; both
                                    saves dated copies next to the current files
  starchaser backup run [--auto]    the backup itself (the starchaser backup user service): --auto only when the
                                    drive is plugged in and a backup is due, and says so when there was none for 7 days

Built on restic (Arch extra). Backups live on the drive in "Starchaser Backups/<your account name>". A password, if
you set one, encrypts them and is kept in your login keyring so backups can run by themselves.
Changes print JSON ({"ok": true, ...} or {"ok": false, "errors": "..."}) and exit 1 when they fail.
"""
import base64
import fcntl
import hashlib
import json
import os
import re
import selectors
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from datetime import datetime
from pathlib import Path
from collections import deque

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams, usage_error  # noqa: E402

PROG = "starchaser backup"
COMMANDS = {"computers": "computers", "password": "password (new and repeat JSON on stdin)", "offer": "offer", "network": "network LOCATION (password JSON on stdin)", "status": "status", "drives": "drives", "use": "use UUID", "set": "set schedule|skip-vms VALUE", "start": "start",
            "stop-using": "stop-using", "snapshots": "snapshots", "files": "files ID [FOLDER]", "restore-plan": "restore-plan ID [PATH ...]", "preview": "preview ID PATH",
            "restore-start": "restore-start ID home|FOLDER [PATH ...]", "run": "run [--auto]"}
INTERNAL = {"restore": "restore ID home|FOLDER [PATH ...]"}       # restore-start's worker
AREA = "/usr/local/lib/starchaser/starchaser-admin-area"
HOME = Path.home()
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME") or HOME / ".config") / "starchaser/backup.json"
STATE_DIR = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser"
STATE = STATE_DIR / "backup.json"
HEALTH = Path("/var/lib/starchaser/drive-health.json")
RESTORED = STATE_DIR / "backup-restore.json"
LOCK = STATE_DIR / "backup.lock"
WANTED = STATE_DIR / "backup.wanted"            # "Back up now" was pressed: the next run counts as due
FOLDER = "Starchaser Backups"
SCHEDULES = {"hourly": 3600, "daily": 86400, "weekly": 7 * 86400}
OVERDUE_DAYS = 7
# drives formatted for other computers too (exFAT, FAT, NTFS) and Linux ones; a locked encrypted drive has no files yet
FILESYSTEMS = {"ext4", "ext3", "btrfs", "xfs", "f2fs", "exfat", "vfat", "ntfs", "ntfs3"}
SYSTEM_MOUNTS = ("/", "/boot", "/efi", "/home", "/var", "/usr", "[SWAP]")
UUID = re.compile(r"[A-Za-z0-9-]{1,64}\Z")
SNAP_ID = re.compile(r"[0-9a-f]{8,64}\Z")
NO_TOOL = "The backup tool isn't installed. Press Install the backup tool in Settings > Backups."
KEYRING = ("xdg:schema", "org.starchaser.Backup")
KEYRING_LOCKED = ("Your saved sign-ins are locked (automatic sign-in leaves them locked), so the backup password can't "
                  "be read yet. Starchaser asks for your sign-in password when a backup is due.")
# kept: every backup of the last day, a day for two weeks, a week for two months, a month for two years
KEEP = ["--keep-hourly", "24", "--keep-daily", "14", "--keep-weekly", "8", "--keep-monthly", "24"]
PRUNE_EVERY = 7 * 86400
CHECK_EVERY = 30 * 86400


class Failed(Exception):
    pass


class DriveFull(Failed):
    pass


class KeyringLocked(Failed):
    """The backup password is saved, but the keyring holding it is locked (automatic sign-in leaves it locked)."""


# ---------------------------------------------------------------- small helpers

def run(args, timeout=60, env=None, input_text=None):
    try:
        return subprocess.run(args, capture_output=True, text=True, timeout=timeout, env=env, input=input_text,
                              stdin=subprocess.DEVNULL if input_text is None else None)
    except subprocess.TimeoutExpired:
        return subprocess.CompletedProcess(args, 124, "", "timed out")
    except OSError as e:
        return subprocess.CompletedProcess(args, 127, "", str(e))


def jread(path, default):
    try:
        data = json.loads(path.read_text())
    except (OSError, ValueError, RecursionError):
        return default
    return data if isinstance(data, dict) else default


def jwrite(path, data):
    """Whole or not at all: a per-process temp file next to it, fsynced, renamed over it."""
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    with open(tmp, "w") as f:
        f.write(json.dumps(data))
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)


def update_state(**changes):
    """Read-modify-write of the state file, under its own lock (the service and Settings both write it)."""
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    with open(STATE_DIR / "backup-state.lock", "a") as lk:
        fcntl.flock(lk, fcntl.LOCK_EX)
        state = jread(STATE, {})
        state.update(changes)
        jwrite(STATE, state)
        return state


def size_text(b):
    """Decimal units, as the drive's box says: small amounts keep their detail (400 MB is not "0 GB")."""
    b = max(0, int(b or 0))
    if b >= 1e12:
        return f"{b / 1e12:.1f} TB"
    if b >= 10e9:
        return f"{round(b / 1e9)} GB"
    if b >= 1e9:
        return f"{b / 1e9:.1f} GB"
    if b >= 1e6:
        return f"{round(b / 1e6)} MB"
    return f"{round(b / 1e3)} KB" if b >= 1e3 else f"{b} bytes"


def clock(t):
    return t.strftime("%I:%M %p").lstrip("0")


def when(ts, now=None):
    """"Today at 3:15 PM", "Yesterday at 9:02 AM", "Nov 3 at 10:00 AM", "Nov 3, 2025"."""
    t, n = datetime.fromtimestamp(ts), datetime.fromtimestamp(now or time.time())
    days = (n.date() - t.date()).days
    if days == 0:
        return f"Today at {clock(t)}"
    if days == 1:
        return f"Yesterday at {clock(t)}"
    if t.year == n.year:
        return f"{t.strftime('%b')} {t.day} at {clock(t)}"
    return f"{t.strftime('%b')} {t.day}, {t.year}"


def ago(ts, now=None):
    s = max(0, (now or time.time()) - ts)
    if s < 120:
        return "just now"
    for unit, size in (("day", 86400), ("hour", 3600), ("minute", 60)):
        if s >= size:
            n = int(s // size)
            return f"{n} {unit}{'' if n == 1 else 's'} ago"
    return "just now"


def stamp(text):
    """restic's RFC 3339 times (nanoseconds, any offset) as epoch seconds; 0 when unreadable."""
    m = re.match(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?(Z|[+-]\d\d:\d\d)?", str(text or ""))
    if not m:
        return 0.0
    zone = m.group(3) or "+00:00"
    try:
        t = datetime.fromisoformat(m.group(1) + ("+00:00" if zone == "Z" else zone)).timestamp()
    except ValueError:
        return 0.0
    return t + (float("0." + m.group(2)) if m.group(2) else 0.0)


def safe_rel(rel):
    """A path inside the Home folder, relative, with no way out of it ("..", an absolute path)."""
    parts = [p for p in str(rel).split("/") if p not in ("", ".")]
    if not parts or any(p == ".." for p in parts) or "\0" in str(rel):
        raise Failed("That file isn't inside your Home folder.")
    return "/".join(parts)


# ---------------------------------------------------------------- what to copy

def excludes(home, skip_vms):
    """What a backup leaves out: caches and the trash (they come back by themselves or were thrown away), and with
    skip_vms the disks of virtual machines (often tens of GB, and changed whole every time one runs)."""
    h = str(home)
    out = [f"{h}/.cache", f"{h}/.local/share/Trash", f"{h}/.var/app/*/cache", f"{h}/.thumbnails",
           f"{h}/.local/share/flatpak/repo/tmp"]
    if skip_vms:
        out += [f"{h}/.local/share/libvirt/images", f"{h}/VirtualBox VMs", f"{h}/.local/share/containers/storage",
                "*.qcow2", "*.vdi", "*.vmdk", "*.vhd", "*.vhdx"]
    return out


def due(conf, state, now, wanted=False):
    """Whether a backup should run now: asked for, never done, or the schedule's time since the last good one."""
    if wanted:
        return True
    last = float(state.get("last") or 0)
    # the timer starts each run up to 5 min late (RandomizedDelaySec), so a tick that drew less delay than the last one
    # still counts; last is when that backup started, so how long it took doesn't push the next one out a tick
    return now - last >= SCHEDULES.get(conf.get("schedule"), SCHEDULES["daily"]) - 600


def overdue_days(conf, state, now):
    """Whole days without a backup once that reaches OVERDUE_DAYS (counted from when backups were set up when
    there has never been one), else 0."""
    if not conf.get("uuid"):
        return 0
    since = float(state.get("last") or conf.get("since") or now)
    days = int((now - since) // 86400)
    return days if days >= OVERDUE_DAYS else 0


# ---------------------------------------------------------------- drives

def udisks_hints(dev):
    """udisks' own word on a device: HintSystem false is a removable or external drive, the kind it lets the person
    at the computer mount without a password; HintIgnore true is one the desktop hides."""
    r = run(["udisksctl", "info", "-b", dev], timeout=10)
    hints = {}
    for line in r.stdout.splitlines():
        m = re.match(r"\s*(HintSystem|HintIgnore):\s*(\w+)", line)
        if m and m.group(1) not in hints:
            hints[m.group(1)] = m.group(2) == "true"
    return hints if r.returncode == 0 else {}


def flat(devices, parent=None):
    for d in devices or []:
        d = dict(d, parent=parent)
        yield d
        yield from flat(d.get("children"), d)


def parse_drives(tree, hints=udisks_hints):
    """The partitions a backup can go to, from lsblk's JSON: a filesystem with a UUID, on a disk udisks calls
    external, and no part of the disk running this computer."""
    rows = list(flat(tree.get("blockdevices")))
    system_disks = set()
    for d in rows:
        if any(m in SYSTEM_MOUNTS for m in d.get("mountpoints") or [] if m):
            top = d
            while top.get("parent"):
                top = top["parent"]
            system_disks.add(top.get("path"))
    out = []
    for d in rows:
        top = d
        while top.get("parent"):
            top = top["parent"]
        if not d.get("uuid") or (d.get("fstype") or "") not in FILESYSTEMS or top.get("path") in system_disks:
            continue
        h = hints(d["path"])
        if h.get("HintSystem", True) or h.get("HintIgnore"):
            continue
        model = " ".join(w for w in ((top.get("vendor") or "").strip(), (top.get("model") or "").strip()) if w)
        size = int(d.get("size") or 0)
        name = (d.get("label") or "").strip() or model or f"{size_text(size)} drive"
        mounts = [m for m in d.get("mountpoints") or [] if m]
        out.append({"uuid": d["uuid"], "name": name, "model": model, "size": size, "sizeText": size_text(size),
                    "free": int(d["fsavail"]) if d.get("fsavail") not in (None, "") else None, "fstype": d["fstype"],
                    "mounted": mounts[0] if mounts else ""})
    return out


def lsblk():
    r = run(["lsblk", "-J", "-b", "-o", "PATH,UUID,LABEL,FSTYPE,SIZE,FSAVAIL,MOUNTPOINTS,TYPE,MODEL,VENDOR"], timeout=15)
    try:
        return json.loads(r.stdout) if r.returncode == 0 else {}
    except ValueError:
        return {}


def drives():
    return parse_drives(lsblk())


def plugged(uuid):
    conf = jread(CONFIG, {})
    if conf.get('uuid') == uuid and conf.get('network'):
        return True  # restic reports an unavailable server; it must not be mistaken for an unplugged USB
    return bool(uuid) and os.path.exists(f"/dev/disk/by-uuid/{uuid}")


def mounted_at(uuid):
    for d in flat(lsblk().get("blockdevices")):
        if d.get("uuid") == uuid:
            mounts = [m for m in d.get("mountpoints") or [] if m]
            return mounts[0] if mounts else ""
    return ""


def mount(uuid):
    """(where the drive is mounted, whether this call mounted it); udisks mounts it the way the file manager does.
    The state file notes a drive this mounted, so whichever run ends last puts it away (put_away)."""
    where = mounted_at(uuid)
    if where:
        return where, False
    r = run(["udisksctl", "mount", "-b", f"/dev/disk/by-uuid/{uuid}", "--no-user-interaction"], timeout=60)
    where = mounted_at(uuid)        # also when something else (the file manager) mounted it at the same moment
    if not where:
        raise Failed("The backup drive couldn't be opened. Unplug it, plug it in again, and try again."
                     + (f" ({r.stderr.strip().splitlines()[-1]})" if r.stderr.strip() else ""))
    if r.returncode == 0:
        update_state(mountedBy=uuid)
    return where, r.returncode == 0


def unmount(uuid):
    run(["udisksctl", "unmount", "-b", f"/dev/disk/by-uuid/{uuid}", "--no-user-interaction"], timeout=60)   # best-effort
    if jread(STATE, {}).get("mountedBy") == uuid and not mounted_at(uuid):
        update_state(mountedBy="")


def put_away(uuid, mounted_now, others_busy):
    """Unmount the drive when backups mounted it (this call, or an earlier one: the list of backups, a folder in it,
    choosing the drive), so it stays safe to unplug as it was before. A backup or restore still using it puts it away
    when it ends instead."""
    if uuid and (mounted_now or jread(STATE, {}).get("mountedBy") == uuid) and not others_busy:
        unmount(uuid)


def restoring():
    restore = jread(RESTORED, {})
    return bool(restore.get("running")) and pid_alive(restore.get("pid"))


def device_unit(uuid):
    r = run(["systemd-escape", "--path", "--suffix=device", f"/dev/disk/by-uuid/{uuid}"], timeout=5)
    return r.stdout.strip() if r.returncode == 0 else ""


# ---------------------------------------------------------------- restic

def restic_version():
    """(installed, new enough) — 0.17 brought backups without a password and restore's --overwrite."""
    r = run(["restic", "version"], timeout=10)
    if r.returncode:
        return False, False
    m = re.search(r"restic (\d+)\.(\d+)", r.stdout)
    return True, bool(m) and (int(m.group(1)), int(m.group(2))) >= (0, 17)


def repo_path(where, owner=None):
    owner = owner or os.environ.get("USER") or HOME.name
    if owner in (".", "..") or "/" in owner or "\0" in owner:
        raise Failed("Choose whose backups to use.")
    base = Path(where) / FOLDER
    repo = base / owner
    if base.is_symlink() or repo.is_symlink():
        raise Failed("The backup folder is a link. Choose another drive.")
    return repo


def backup_owners(where):
    base = Path(where) / FOLDER
    if base.is_symlink():
        raise Failed("The backup folder is a link. Choose another drive.")
    try:
        base.stat()
    except FileNotFoundError:
        return []
    except OSError:
        raise Failed("The backups on this drive couldn't be listed. Ask an administrator to help.") from None
    try:
        owners = []
        for p in base.iterdir():
            if not stat.S_ISDIR(p.lstat().st_mode):
                continue
            try:
                found = has_repository(p)
            except Failed:
                # A private folder may hold another account's backups. Offer its
                # name, then explain the permissions if the person selects it.
                found = True
            if found:
                owners.append(p.name)
        return sorted(owners)
    except OSError:
        raise Failed("The backups on this drive couldn't be listed. Ask an administrator to help.") from None


def has_repository(repo):
    # Path.is_file() hides permission errors on some Python versions. Only a
    # missing config is evidence that initialization may be appropriate.
    try:
        return stat.S_ISREG((repo / "config").stat().st_mode)
    except FileNotFoundError:
        return False
    except OSError:
        raise Failed("These backups couldn't be read. Ask an administrator to help open this account's backup folder.") from None


def keyring_saved(uuid):
    """"unlocked", "locked" or "missing" for the saved backup password, or "" when the keyring service doesn't answer.
    Asks the service without unlocking anything, so nothing pops up."""
    r = run(["busctl", "--user", "--json=short", "call", "org.freedesktop.secrets", "/org/freedesktop/secrets",
             "org.freedesktop.Secret.Service", "SearchItems", "a{ss}", "2", *KEYRING, "uuid", uuid], timeout=10)
    try:
        unlocked, locked = json.loads(r.stdout)["data"] if r.returncode == 0 else ((), ())
    except (ValueError, KeyError, TypeError):
        return ""
    if r.returncode:
        return ""
    return "unlocked" if unlocked else "locked" if locked else "missing"


def keyring_get(uuid, unlock=True):
    """The saved backup password, or None when none is saved. unlock=False (an automatic backup nobody asked for)
    never brings up the keyring's unlock question: a locked keyring raises KeyringLocked instead."""
    saved = keyring_saved(uuid)
    if saved == "missing":
        return None
    if saved == "locked" and not unlock:
        raise KeyringLocked(KEYRING_LOCKED)
    r = run(["secret-tool", "lookup", *KEYRING, "uuid", uuid], timeout=20)
    if r.returncode == 0 and r.stdout:
        return r.stdout
    if saved == "locked" or keyring_saved(uuid) == "locked":           # the unlock question was canceled or timed out
        raise KeyringLocked(KEYRING_LOCKED)
    return None


def keyring_set(uuid, name, password):
    r = run(["secret-tool", "store", "--label", f"Backup password ({name})", *KEYRING, "uuid", uuid], timeout=30,
            input_text=password)
    return r.returncode == 0


def keyring_clear(uuid):
    run(["secret-tool", "clear", *KEYRING, "uuid", uuid], timeout=20)       # best-effort: nothing saved is fine too


def restic(repo, password, *args, timeout=600):
    """restic on one repository. password None: a backup made without one (restic's --insecure-no-password)."""
    env = {k: v for k, v in os.environ.items() if not k.startswith("RESTIC_")}
    env.update(RESTIC_REPOSITORY=str(repo), LC_ALL="C")
    flags = []
    if password is None:
        flags = ["--insecure-no-password"]
    else:
        env["RESTIC_PASSWORD"] = password
    flags += network_flags(repo)
    return run(["restic", *flags, *args], timeout=timeout, env=env), env, flags


# restic's own words for its common failures (LC_ALL=C keeps them English), and what the person can do
RESTIC_FAILURES = (
    (("unable to open config file", "is there a repository at the following location"),
     "The backups on the drive couldn't be found. Choose the drive again in Settings > Backups."),
    (("repository contains errors", "ciphertext verification failed", "invalid data returned", "checksum mismatch",
      "unexpected eof", "not found in index", "is damaged", "load index"),
     "The backups on the drive are damaged. Your files on this computer are fine. Choose another drive in "
     "Settings > Backups to keep backing up."),
    (("input/output error",),
     "The backup drive couldn't be read or written. Unplug it, plug it in again, and try again. If it keeps "
     "happening, the drive may be failing: use another one."),
    (("read-only file system",),
     "The backup drive can only be read, not written. Unplug it, plug it in again, and try again."),
    (("permission denied",),
     "Your account can't write to the backups on the drive. Choose the drive again in Settings > Backups."),
)


def restic_error(r):
    """A plain sentence for a failed restic run. restic's own last line goes to the log (the journal for automatic
    backups), never on screen."""
    lines = [ln for ln in (r.stderr or "").strip().splitlines() if ln.strip()]
    if lines:
        print(f"{PROG}: restic exited {r.returncode}: {lines[-1]}", file=sys.stderr, flush=True)
    if r.returncode == 12 or any("wrong password" in ln for ln in lines):
        return "The backup password didn't match. Choose the drive again in Settings > Backups and type its password."
    if r.returncode == 11 or any("unable to create lock" in ln or "repository is already locked" in ln for ln in lines):
        return "The backups on the drive are in use by another backup or restore. Try again in a few minutes."
    if any("no space left" in ln.lower() for ln in lines):
        return "The backup drive is full. Use a bigger drive, or free up space on it."
    if r.returncode == 124:
        return "The backup drive took too long to answer. Unplug it, plug it in again, and try again."
    text = " ".join(lines).lower()
    for words, sentence in RESTIC_FAILURES:
        if any(w in text for w in words):
            return sentence
    return "Something went wrong with the backup drive or the backups on it. Unplug the drive, plug it in again, and try again."


def repo_id(repo, password):
    """The id restic gave the backups when they were started: another drive can copy the filesystem's UUID, never this
    (without a password the id is only as secret as the drive itself, which already holds the backups)."""
    r, _, _ = restic(repo, password, "cat", "config", "--no-lock", timeout=120)
    if r.returncode:
        raise Failed(restic_error(r))
    try:
        found = json.loads(r.stdout).get("id")
    except (ValueError, AttributeError):
        found = None
    if not found or not isinstance(found, str):
        raise Failed("The backups on the drive couldn't be read. Choose the drive again in Settings > Backups.")
    return found


def open_drive(conf, unlock=True):
    """Mount the chosen drive and find its backups: (repository, password, whether this mounted the drive). Only the
    backups chosen in Settings > Backups: a drive made to look like it (the same filesystem UUID) gets nothing."""
    uuid = conf.get("uuid", "")
    if conf.get('network'):
        repo = network_location(conf['network'])
        password = keyring_get(uuid, unlock)
        if password is None:
            raise Failed(KEYRING_LOCKED)
        if repo_id(repo, password) != conf.get('repoId'):
            raise Failed('This network location no longer holds the backups you chose. Nothing was copied. Choose it again in Settings > Backups.')
        return repo, password, False
    if not plugged(uuid):
        raise Failed(f"Plug in {conf.get('name') or 'your backup drive'} to use your backups.")
    where, mounted_now = mount(uuid)
    repo = repo_path(where, conf.get("owner"))
    if not has_repository(repo):
        raise Failed(f"The backups aren't on {conf.get('name') or 'the drive'} any more. Choose the drive again in Settings > Backups.")
    password = None
    if conf.get("encrypted"):
        password = keyring_get(uuid, unlock)
        if password is None:
            raise Failed("The backup password couldn't be read from your keyring. Choose the drive again in Settings > Backups and type its password.")
    found = repo_id(repo, password)
    if not conf.get("repoId"):
        write_conf(dict(conf, repoId=found))            # chosen before the id was kept: these are the backups it used
    elif found != conf["repoId"]:
        raise Failed(f"The drive plugged in as {conf.get('name') or 'your backup drive'} doesn't hold your backups, so "
                     "nothing was copied to or from it. If it is your backup drive, choose it again in Settings > Backups.")
    return repo, password, mounted_now


# ---------------------------------------------------------------- notices

def notify(summary, body, low=True, seconds=6):
    """Quiet by default: low urgency makes no sound and doesn't count as unread; one notice that replaces itself."""
    run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "drive-harddisk", "-u", "low" if low else "normal", "-t", str(seconds * 1000),
         "-h", "string:x-canonical-private-synchronous:starchaser-backup", summary, body], timeout=10)


# ---------------------------------------------------------------- reading

def running():
    """Whether a backup holds the lock now (taken and let go at once if nobody does)."""
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    with open(LOCK, "a") as lk:
        try:
            fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            return True
        fcntl.flock(lk, fcntl.LOCK_UN)
    return False


AUTOMATIC_SIGN_IN_WARNING = ("This computer signs in by itself, so after a restart the backup password stays locked until you type your sign-in password once. Starchaser asks when a backup is due.")


def automatic_sign_in():
    try:
        r = run(['/usr/local/lib/starchaser/starchaser-admin', 'autologin'], timeout=5)
        result = json.loads(r.stdout)
        return r.returncode == 0 and result.get('on') is True and result.get('user') == HOME.name
    except (OSError, ValueError, subprocess.TimeoutExpired):
        return False


def status():
    installed, recent = restic_version()
    conf, state, now = jread(CONFIG, {}), jread(STATE, {}), time.time()
    out = {"ok": True, "automaticSignIn": automatic_sign_in(), "installed": installed, "tooOld": installed and not recent, "configured": bool(conf.get("uuid"))}
    restore = jread(RESTORED, {})
    if restore.get("running") and not pid_alive(restore.get("pid")):
        restore = dict(restore, running=False, ok=False, message="The restore stopped before it finished. Try again.")
    out["restore"] = restore
    if not conf.get("uuid"):
        return out
    uuid = conf["uuid"]
    is_running = running()
    last = float(state.get("last") or 0)
    days = overdue_days(conf, state, now)
    where = mounted_at(uuid) if plugged(uuid) and not conf.get("network") else ""
    free = None
    if where:
        try:
            free = shutil.disk_usage(where).free
        except OSError:
            free = None
    out.update(network=conf.get("network", ""), drive={"uuid": uuid, "name": conf.get("name", "")}, schedule=conf.get("schedule", "daily"),
               owner=conf.get("owner") or HOME.name, ownerCount=len(backup_owners(where)) if where else 1, encrypted=bool(conf.get("encrypted")), skipVms=conf.get("skipVms", True) is not False,
               plugged=plugged(uuid), mounted=where, running=is_running,
               progress=state.get("progress") if is_running else None,
               remainingText=remaining_text(state, now) if is_running else "",
               last=last, lastText=f"{ago(last, now)} ({when(last, now)})" if last else "",
               overdueDays=days, used=state.get("used"), usedText=size_text(state["used"]) if state.get("used") else "",
               free=free, freeText=size_text(free) if free is not None else "",
               checked=state.get("checked", 0), checkedText=when(state["checked"]) if state.get("checked") else "",
               passwordMade=conf.get("passwordMade") or conf.get("since", 0),
               passwordMadeText=when(conf.get("passwordMade") or conf.get("since", 0)) if conf.get("passwordMade") or conf.get("since") else "",
               thinned=bool(state.get("thinned")),
               error="" if is_running else state.get("error", ""))
    return out


def remaining_text(state, now=None):
    """Only copying has an estimate; late or incomplete samples do not imply time left."""
    now = time.time() if now is None else now
    measured = float(state.get('measured') or 0)
    seconds = state.get('remaining')
    if seconds is None or seconds < 0 or now - measured > 15 or measured > now:
        return ''
    seconds = max(0, seconds - (now - measured))
    minutes = max(1, int((seconds + 59) // 60))
    return 'Less than a minute left' if seconds < 60 else f'About {minutes} minute{"" if minutes == 1 else "s"} left'


def pid_alive(pid):
    try:
        os.kill(int(pid), 0)
    except (TypeError, ValueError, ProcessLookupError):
        return False
    except PermissionError:
        return True
    return True


def snapshots():
    conf = jread(CONFIG, {})
    if not conf.get("uuid"):
        raise Failed("Choose a backup drive first.")
    mounted_now = False
    try:       # open_drive can mount the drive and then refuse it: put_away (by mountedBy) unmounts it then too
        repo, password, mounted_now = open_drive(conf)
        r, _, _ = restic(repo, password, "snapshots", "--json", "--no-lock", timeout=120)
    finally:
        put_away(conf["uuid"], mounted_now, running() or restoring())
    if r.returncode:
        raise Failed(restic_error(r))
    try:
        snaps = json.loads(r.stdout) or []
    except ValueError:
        raise Failed("The list of backups couldn't be read. Try again.") from None
    host = os.uname().nodename
    rows = []
    for s in snaps:
        t = stamp(s.get("time"))
        summary = s.get("summary") or {}
        rows.append({"id": s.get("id", ""), "short": s.get("short_id", ""), "time": t, "text": when(t),
                     "host": s.get("hostname", ""), "otherComputer": s.get("hostname", "") != host,
                     "root": (s.get("paths") or [""])[0], "files": summary.get("total_files_processed"),
                     "bytes": summary.get("total_bytes_processed")})
    rows.sort(key=lambda x: -x["time"])
    return {"ok": True, "snapshots": rows}


def snapshot_root(repo, password, snap):
    r, _, _ = restic(repo, password, "snapshots", "--json", "--no-lock", snap, timeout=120)
    try:
        found = json.loads(r.stdout) if r.returncode == 0 else []
    except ValueError:
        found = []
    if not found or not (found[0].get("paths") or []):
        raise Failed("That backup isn't on the drive any more. Look at the list again.")
    return found[0]["paths"][0].rstrip("/") or "/"


def ls_nodes(text):
    for line in (text or "").splitlines():
        try:
            n = json.loads(line)
        except ValueError:
            continue
        if isinstance(n, dict) and (n.get("struct_type") == "node" or n.get("message_type") == "node"):
            yield n


def files(snap, rel=""):
    if not SNAP_ID.match(snap):
        raise Failed("That isn't a backup on the drive.")
    rel = safe_rel(rel) if rel.strip("/.") else ""
    conf = jread(CONFIG, {})
    mounted_now = False
    try:       # as in snapshots(): a refusal after the mount still puts the drive away
        repo, password, mounted_now = open_drive(conf)
        root = snapshot_root(repo, password, snap)
        folder = root + ("/" + rel if rel else "")
        r, _, _ = restic(repo, password, "ls", "--json", "--no-lock", snap, folder, timeout=300)
    finally:
        put_away(conf.get("uuid", ""), mounted_now, running() or restoring())
    if r.returncode:
        raise Failed(restic_error(r))
    rows = []
    for n in ls_nodes(r.stdout):
        path = n.get("path", "")
        if path.rstrip("/") == folder or os.path.dirname(path.rstrip("/")) != folder:
            continue                                    # the folder itself, or (older restic) something deeper
        rows.append({"name": n.get("name", ""), "path": path[len(root):].lstrip("/"), "folder": n.get("type") == "dir", "previewable": n.get("type") == "file",
                     "size": n.get("size") or 0, "sizeText": "" if n.get("type") == "dir" else size_text(n.get("size")),
                     "time": stamp(n.get("mtime")), "changedText": datetime.fromtimestamp(stamp(n.get("mtime"))).strftime("%b %-d, %-I:%M %p")})
    rows.sort(key=lambda x: (x["name"].startswith("."), not x["folder"], x["name"].lower()))     # Documents before .config
    return {"ok": True, "folder": rel, "files": rows}


PREVIEW_LIMIT = 8 * 1024 * 1024


def preview(snap, rel):
    """Read one regular file into memory. No extraction, executable app or live file is involved."""
    if not SNAP_ID.fullmatch(snap):
        raise Failed("That isn't a backup on the drive.")
    if Path(rel).is_absolute():
        raise Failed("Choose a file relative to your Home folder.")
    rel = safe_rel(rel)
    if not rel:
        raise Failed('Choose a file to preview.')
    conf, mounted_now = jread(CONFIG, {}), False
    try:
        repo, password, mounted_now = open_drive(conf)
        root = snapshot_root(repo, password, snap)
        path = root + '/' + rel
        listed, _, _ = restic(repo, password, 'ls', '--json', '--no-lock', snap, path, timeout=120)
        if listed.returncode:
            raise Failed(restic_error(listed))
        nodes = [n for n in ls_nodes(listed.stdout) if n.get('path') == path]
        if len(nodes) != 1 or nodes[0].get('type') != 'file':
            raise Failed("Only a regular file can be previewed. Links and folders aren't opened.")
        if not isinstance(nodes[0].get('size'), int) or not 0 <= nodes[0]['size'] <= PREVIEW_LIMIT:
            raise Failed('This file is too large to preview. Restore it in a new folder to look at it.')
        data = preview_bytes(repo, password, snap, path)
        if len(data) != nodes[0]['size']:
            raise Failed("The saved copy couldn't be read completely. Nothing was restored.")
        result = {'ok': True, 'name': Path(rel).name, 'date': nodes[0].get('mtime', ''), 'sizeText': size_text(len(data))}
        mime = 'image/png' if data.startswith(b'\x89PNG\r\n\x1a\n') else 'image/jpeg' if data.startswith(b'\xff\xd8\xff') else ''
        if mime:
            return dict(result, image='data:' + mime + ';base64,' + base64.b64encode(data).decode(), text='')
        try:
            if data.startswith(b'%PDF-'):
                raise ValueError('unsupported document')
            text = data.decode('utf-8')
            if any(ord(c) < 32 and c not in '\n\r\t' for c in text):
                raise ValueError('binary')
            result.update(text=text[:262144], hint='Only the first part is shown.' if len(text) > 262144 else '')
        except (UnicodeDecodeError, ValueError):
            result.update(text='', hint="This kind of file can't be shown here. To look at it, choose it, pick “In a new folder” and restore it. Your current file stays as it is.")
        return result
    finally:
        put_away(conf.get('uuid', ''), mounted_now, running() or restoring())


def preview_bytes(repo, password, snap, path):
    env = {k: v for k, v in os.environ.items() if not k.startswith('RESTIC_')}
    env.update(RESTIC_REPOSITORY=str(repo), LC_ALL='C')
    flags = ['--insecure-no-password'] if password is None else []
    if password is not None:
        env['RESTIC_PASSWORD'] = password
    # Read at most one bounded file, even if repository metadata understates its size.
    with tempfile.TemporaryFile() as errors, subprocess.Popen(
            ['restic', *network_flags(repo), *flags, 'dump', snap, path], env=env,
            stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=errors) as process:
        data = bytearray()
        deadline = time.monotonic() + 120
        try:
            with selectors.DefaultSelector() as selector:
                selector.register(process.stdout, selectors.EVENT_READ)
                while True:
                    left = deadline - time.monotonic()
                    if left <= 0 or not selector.select(left):
                        raise Failed('The saved copy took too long to open. Nothing was restored.')
                    chunk = os.read(process.stdout.fileno(), min(65536, PREVIEW_LIMIT + 1 - len(data)))
                    if not chunk:
                        break
                    data.extend(chunk)
                    if len(data) > PREVIEW_LIMIT:
                        raise Failed('This file is too large to preview. Nothing was restored.')
                if process.wait(timeout=max(1, deadline - time.monotonic())) != 0:
                    raise Failed("The saved copy couldn't be read. Nothing was restored.")
        except (Failed, subprocess.TimeoutExpired):
            process.kill()
            process.wait()
            raise Failed("The saved copy couldn't be read within the preview limits. Nothing was restored.") from None
    return bytes(data)


# ---------------------------------------------------------------- changes

def write_conf(conf):
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    with open(STATE_DIR / "backup-config.lock", "a") as lk:
        fcntl.flock(lk, fcntl.LOCK_EX)
        jwrite(CONFIG, conf)


def make_folder(where, repo):
    """The backup folder on the drive, made as you when its top folder lets you; the computer's own top folder
    (a drive formatted for Linux) goes through starchaser-admin, which makes it yours (asks for your password)."""
    try:
        repo.mkdir(parents=True, exist_ok=True, mode=0o700)
        return
    except PermissionError:
        pass
    except OSError as e:
        raise Failed(f"The backup folder couldn't be made on the drive ({e.strerror}).") from None
    r = run(["pkexec", AREA, "backup-folder", str(where)], timeout=180)
    if r.returncode == 126 or (r.returncode == 127 and not r.stdout.strip()):
        raise Failed("No change made.")
    try:
        result = json.loads(r.stdout)
    except ValueError:
        result = {}
    if r.returncode or not result.get("ok"):
        raise Failed(result.get("errors") or "The backup folder couldn't be made on the drive. Try again.")
    if not os.access(repo, os.W_OK):
        raise Failed("The backup folder on the drive belongs to another account. Use another drive.")


def use(uuid, answer):
    """Choose the drive. The drive stays mounted for the first backup, which starts at once and puts it away; when
    choosing it doesn't work out, it is put away here."""
    if not UUID.match(uuid):
        raise Failed("That isn't a drive.")
    done = False
    try:
        result = choose(uuid, answer)
        done = result.get("ok", False)
        return result
    finally:
        if not done:
            put_away(uuid, False, running() or restoring())


def choose(uuid, answer):
    if not UUID.match(uuid):
        raise Failed("That isn't a drive.")
    installed, recent = restic_version()
    if not installed or not recent:
        raise Failed(NO_TOOL)
    drive = next((d for d in drives() if d["uuid"] == uuid), None)
    if not drive:
        raise Failed("That drive isn't plugged in any more, or isn't an external drive. Plug it in and look at the list again.")
    password = str(answer.get("password") or "")
    encrypt = bool(answer.get("encrypt"))
    where, _ = mount(uuid)
    owners = backup_owners(where)
    owner = answer.get("owner")
    own_repo = repo_path(where)
    separate = answer.get("new") is True or (owner == own_repo.name and owner not in owners)
    if owners and not owner and not separate:
        return {"ok": False, "needOwner": True, "owners": owners,
                "errors": "Choose whose backups to use, or start separate backups for your account."}
    if owner and owner not in owners and not separate:
        raise Failed("Those backups are no longer on this drive. Choose the drive again.")
    repo = own_repo if separate else repo_path(where, owner)
    adopted = has_repository(repo)
    if separate and adopted:
        raise Failed("Your account already has backups on this drive. Choose those backups to use them.")
    if adopted:
        # backups already on the drive (this computer before, or one that was replaced): use them as they are
        r, _, _ = restic(repo, None, "cat", "config", "--no-lock", timeout=120)
        if r.returncode == 0:
            encrypt, password = False, ""
        elif not password:
            return {"ok": False, "needPassword": True, "name": drive["name"],
                    "errors": f"{drive['name']} already has backups, protected by a password. Type that password to use them."}
        else:
            r, _, _ = restic(repo, password, "cat", "config", "--no-lock", timeout=120)
            if r.returncode:
                return {"ok": False, "needPassword": True, "name": drive["name"], "errors": "That password didn't open the backups on the drive. Try again."}
            encrypt = True
    elif encrypt and len(password) < 8:
        raise Failed("Use a password of at least 8 characters, or turn off the password.")
    if encrypt and not keyring_set(uuid, drive["name"], password):
        raise Failed("The password couldn't be saved in your keyring, so backups couldn't run by themselves. Nothing was changed.")
    if not adopted:
        make_folder(where, repo)
        r, _, _ = restic(repo, password if encrypt else None, "init", timeout=300)
        if r.returncode:
            raise Failed(restic_error(r))
    found = repo_id(repo, password if encrypt else None)
    old = jread(CONFIG, {})
    if old.get("uuid") and old["uuid"] != uuid:
        forget_drive(old)
    write_conf({"uuid": uuid, "name": drive["name"], "schedule": old.get("schedule", "daily"), "encrypted": encrypt,
                "skipVms": old.get("skipVms", True), "since": time.time(), "repoId": found, "owner": repo.name})
    if old.get("uuid") != uuid or old.get("repoId") != found:
        update_state(last=0, used=None, error="", progress=None, checked=0, pruned=0, thinned=False)
    arm(uuid)
    start()
    return {"ok": True, "name": drive["name"], "adopted": adopted, "encrypted": encrypt,
            "warning": AUTOMATIC_SIGN_IN_WARNING if encrypt and automatic_sign_in() else ""}



def wants_link(uuid):
    unit = "" if uuid.startswith("network-") else device_unit(uuid)
    return CONFIG.parent.parent / "systemd/user" / f"{unit}.wants/starchaser-backup.service" if unit else None


def arm(uuid):
    """The timer checks every hour; the drive's own device unit starts a backup the moment it is plugged in. That
    link is made by hand: systemctl add-wants refuses a device unit, which has no unit file of its own."""
    link = wants_link(uuid)
    if link:
        r = run(["systemctl", "--user", "show", "-P", "FragmentPath", "starchaser-backup.service"], timeout=30)
        link.parent.mkdir(parents=True, exist_ok=True)
        link.unlink(missing_ok=True)
        link.symlink_to(r.stdout.strip() or "../starchaser-backup.service")
    run(["systemctl", "--user", "daemon-reload"], timeout=30)
    run(["systemctl", "--user", "enable", "--now", "starchaser-backup.timer"], timeout=30)


def forget_drive(conf):
    link = wants_link(conf.get("uuid", ""))
    if link and link.is_symlink():
        link.unlink()
        try:
            link.parent.rmdir()
        except OSError:
            pass
        run(["systemctl", "--user", "daemon-reload"], timeout=30)
    if conf.get("encrypted"):
        keyring_clear(conf.get("uuid", ""))


def stop_using():
    conf = jread(CONFIG, {})
    if conf.get("uuid"):
        forget_drive(conf)
    run(["systemctl", "--user", "disable", "--now", "starchaser-backup.timer"], timeout=30)
    try:
        CONFIG.unlink()
    except FileNotFoundError:
        pass
    update_state(last=0, used=None, error="", progress=None)
    return {"ok": True}


def set_option(key, value):
    conf = jread(CONFIG, {})
    if not conf.get("uuid"):
        raise Failed("Choose a backup drive first.")
    if key == "schedule" and value in SCHEDULES:
        conf["schedule"] = value
    elif key == "skip-vms" and value in ("on", "off"):
        conf["skipVms"] = value == "on"
    else:
        raise Failed("That isn't a backup setting.")
    write_conf(conf)
    return {"ok": True}


def start():
    conf = jread(CONFIG, {})
    if not conf.get("uuid"):
        raise Failed("Choose a backup drive first.")
    if not plugged(conf["uuid"]):
        raise Failed(f"Plug in {conf.get('name') or 'your backup drive'} to back up.")
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    WANTED.touch()
    update_state(error="")
    r = run(["systemctl", "--user", "start", "--no-block", "starchaser-backup.service"], timeout=30)
    if r.returncode:                    # no user manager to ask (a test, a bare session): start it ourselves
        subprocess.Popen([str(Path(__file__).resolve()), "run", "--auto"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return {"ok": True}


def nag(conf, state, now):
    """No backup for a week: say so once a day, quietly enough to keep working, until the drive comes back."""
    days = overdue_days(conf, state, now)
    if days and now - float(state.get("nagged") or 0) >= 86400:
        notify("Your files aren't backed up", f"There has been no backup for {days} days. Plug in "
               f"{conf.get('name') or 'your backup drive'} and the backup starts by itself.", low=False, seconds=12)
        update_state(nagged=now)


def backup(auto):
    conf = jread(CONFIG, {})
    if not conf.get("uuid"):
        return {"ok": True, "skipped": "no drive"}
    now, state = time.time(), jread(STATE, {})
    wanted = WANTED.exists()
    if auto and not plugged(conf["uuid"]):
        nag(conf, state, now)
        return {"ok": True, "skipped": "not plugged in"}
    if auto and not due(conf, state, now, wanted):
        return {"ok": True, "skipped": "not due"}
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    with open(LOCK, "a") as lk:
        try:
            fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            return {"ok": True, "skipped": "already running"}
        WANTED.unlink(missing_ok=True)
        mounted_now = False
        try:
            installed, recent = restic_version()
            if not installed or not recent:
                raise Failed(NO_TOOL)
            repo, password, mounted_now = open_drive(conf, unlock=not auto or wanted)
            update_state(progress=0, started=now, remaining=None, measured=0)
            notify("Backing up your files", f"Copying to {conf.get('name') or 'your backup drive'}. You can keep working.")
            thinned = False
            try:
                warnings = copy_home(repo, password, conf)
            except DriveFull:
                thinned = thin_oldest(repo, password)
                if not thinned:
                    raise Failed("The backup drive is full. Its last backup was kept. Use a bigger drive or free up other files on it.") from None
                update_state(thinned=True)
                try:
                    warnings = copy_home(repo, password, conf)
                except DriveFull:
                    raise Failed("The backup drive is still full after removing older backups. The newest previous backup was kept. Use a bigger drive or free up other files on it.") from None
            if now - float(state.get("checked") or 0) >= CHECK_EVERY:
                # 1/12 of stored data per month; the metadata is checked every time.
                part = int(now // CHECK_EVERY) % 12 + 1
                checked, _, _ = restic(repo, password, "check", "--read-data-subset", f"{part}/12", timeout=6 * 3600)
                if checked.returncode:
                    raise Failed("The backup check didn't finish. " + restic_error(checked))
                update_state(checked=now)
            if now - float(state.get("pruned") or 0) >= PRUNE_EVERY:
                r, _, _ = restic(repo, password, "forget", *KEEP, "--prune", timeout=6 * 3600)
                if r.returncode == 0:
                    update_state(pruned=time.time())
            used = None if conf.get("network") else folder_size(repo)
            update_state(remaining=None, measured=0, last=now, error="", errorShown="", progress=None, used=used, warnings=warnings, thinned=thinned)
            notify("Backup finished", f"Your files are copied to {conf.get('name') or 'your backup drive'}."
                   + (" The oldest backups were removed to make room; the newest previous backup was kept." if thinned else "")
                   + (f" {warnings} file{'' if warnings == 1 else 's'} couldn't be read and were left out." if warnings else ""))
            return {"ok": True}
        except Failed as e:
            state = update_state(error=str(e), progress=None, remaining=None, measured=0)
            quiet = isinstance(e, KeyringLocked) and auto and not wanted     # tried again every hour
            if quiet and not overdue_days(conf, state, now):
                return {"ok": True, "skipped": "keyring locked"}           # Settings > Backups says why
            if state.get("errorShown") != str(e) or (quiet and now - float(state.get("keyringNagged") or 0) >= 7 * 86400):        # each new problem once, not every hour
                notify("Your backup didn't finish", f"{e} Settings > Backups has more.", low=False, seconds=12)
                update_state(errorShown=str(e), **({"keyringNagged": now} if quiet else {}))
            raise
        finally:
            put_away(conf["uuid"], mounted_now, restoring())       # it was put away before: leave it safe to unplug


def copy_home(repo, password, conf):
    """restic backup of the Home folder; returns how many files couldn't be read (restic's exit 3 still saves the rest)."""
    rules = STATE_DIR / "backup-excludes.txt"
    rules.write_text("\n".join(excludes(HOME, conf.get("skipVms", True) is not False)) + "\n")
    env = {k: v for k, v in os.environ.items() if not k.startswith("RESTIC_")}
    env.update(RESTIC_REPOSITORY=str(repo), LC_ALL="C")
    flags = ["--insecure-no-password"] if password is None else []
    if password is not None:
        env["RESTIC_PASSWORD"] = password
    # --one-file-system: folders over the network or another drive mounted inside Home aren't copied
    args = ["restic", *flags, "backup", str(HOME), "--json", "--one-file-system", "--exclude-caches",
            "--exclude-file", str(rules), "--tag", "starchaser"]
    app_manifest()
    args[1:1] = network_flags(repo)
    errors, last_write, summary = 0, 0.0, None
    copy_started = time.monotonic()
    with tempfile.TemporaryFile("w+") as err, subprocess.Popen(args, stdout=subprocess.PIPE, stderr=err, stdin=subprocess.DEVNULL,
                                                                 text=True, env=env) as proc:
        for line in proc.stdout:
            try:
                msg = json.loads(line)
            except ValueError:
                continue
            kind = msg.get("message_type")
            if kind == "summary":
                summary = msg
            elif kind == "error":
                errors += 1
            elif kind == "status" and time.time() - last_write >= 3:
                elapsed = time.monotonic() - copy_started
                done, total = msg.get('bytes_done') or 0, msg.get('total_bytes') or 0
                # Restic reports the total only after scanning; require stable measured work first.
                left = (total - done) * elapsed / done if elapsed >= 10 and done > 0 and total > done else None
                update_state(progress=round(100 * float(msg.get("percent_done") or 0)), remaining=left, measured=time.time())
                last_write = time.time()
        code = proc.wait()
        err.seek(0)
        err = err.read()
    if code not in (0, 3):
        if "no space left" in err.lower():
            raise DriveFull("The backup drive is full.")
        raise Failed(restic_error(subprocess.CompletedProcess(args, code, "", err)))
    if not summary or not summary.get('snapshot_id'):
        raise Failed("The backup tool didn't confirm a completed backup. Your previous backups were kept. Try again.")
    update_state(remaining=None, measured=0, files=summary.get('total_files_processed'), bytes=summary.get('total_bytes_processed'), snapshot=summary['snapshot_id'])
    return (errors or 1) if code == 3 else errors


def thin_oldest(repo, password):
    r, _, _ = restic(repo, password, "snapshots", "--json", timeout=120)
    if r.returncode:
        raise Failed(restic_error(r))
    snaps = sorted(json.loads(r.stdout), key=lambda s: stamp(s.get("time")))
    # Remove only this computer/account's oldest history, never another backup
    # set in the same repository and never its newest successful snapshot.
    ours = [s for s in snaps if s.get("hostname") == os.uname().nodename
            and s.get("paths") == [str(HOME)] and "starchaser" in (s.get("tags") or [])]
    if len(ours) < 2:
        return False
    ids = [s["id"] for s in ours[:-1]]
    r, _, _ = restic(repo, password, "forget", *ids, "--prune", timeout=6 * 3600)
    if r.returncode:
        raise Failed("The backup drive is full and older backups couldn't be removed. " + restic_error(r))
    return True


def folder_size(path):
    total = 0
    for root, _, names in os.walk(path):
        for n in names:
            try:
                total += os.lstat(os.path.join(root, n)).st_blocks * 512
            except OSError:
                pass
    return total


def newer_on_disk(nodes, root, target):
    """The backup's files whose copy at `target` is newer (by its modified time) than the backup's: restoring keeps
    those, and says so. Paths relative to the backed-up folder."""
    kept = []
    for n in nodes:
        if n.get("type") != "file":
            continue
        rel = n.get("path", "")[len(root):].lstrip("/")
        try:
            st = os.lstat(Path(target) / rel)
        except OSError:
            continue
        if st.st_mtime > stamp(n.get("mtime")) + 1:
            kept.append(rel)
    return kept


def new_folder(parent, now=None):
    base = Path(parent) / f"Restored files, {datetime.fromtimestamp(now or time.time()).strftime('%b %-d, %Y')}"
    path, n = base, 2
    while path.exists() or path.is_symlink():
        path, n = Path(f"{base} ({n})"), n + 1
    return path


def restore_plan(snap, paths):
    if not SNAP_ID.match(snap):
        raise Failed("That isn't a backup on the drive.")
    paths = [safe_rel(p) for p in paths]
    conf, mounted_now = jread(CONFIG, {}), False
    try:
        repo, password, mounted_now = open_drive(conf)
        root = snapshot_root(repo, password, snap)
        r, _, _ = restic(repo, password, 'ls', '--json', '--no-lock', '--recursive', snap,
                         *([f'{root}/{p}' for p in paths] or [root]), timeout=3600)
        if r.returncode:
            raise Failed(restic_error(r))
        nodes = {n['path']: n for n in ls_nodes(r.stdout)
                 if n.get('type') in ('file', 'symlink', 'dir') and n['path'].rstrip('/') != root.rstrip('/')}
        files = [path for path, node in nodes.items() if node['type'] != 'dir']
        targets = [HOME / safe_rel(path[len(root):].lstrip('/')) for path in files]
        count = sum(target.exists() or target.is_symlink() for target in targets)
        return {'ok': True, 'files': len(files), 'folders': len(nodes) - len(files), 'replaces': count}
    finally:
        put_away(conf.get('uuid', ''), mounted_now, running() or restoring())


def keep_both_name(path, date, reserved=()):
    limit = os.pathconf(path.parent, 'PC_NAME_MAX')

    def shorten(text, budget):
        result = ''
        for char in text:
            size = len(os.fsencode(char))
            if size > budget:
                break
            result += char
            budget -= size
        return result

    n = 1
    while True:
        marker = ' (from backup ' + date + ')' + (f' ({n})' if n > 1 else '')
        available = limit - len(os.fsencode(marker))
        # Keep the extension when possible, and at least one whole character of the original stem.
        suffix = shorten(path.suffix, available - len(os.fsencode(path.stem[:1])))
        stem = shorten(path.stem, available - len(os.fsencode(suffix)))
        if not stem:
            raise Failed("The dated filename doesn't fit on this drive. Choose a new folder to restore into.")
        candidate = path.with_name(stem + marker + suffix)
        if candidate not in reserved and not candidate.exists() and not candidate.is_symlink():
            return candidate
        n += 1


def place_both(source, home, paths, date, snapshot_home=None):
    # Walk every destination parent without following symlinks, even for folders absent from today's Home.
    # Exclusive creates protect both current files and any previous dated copies.
    made_dirs = []
    destinations = {'.': home}
    reserved = set()
    for rel in sorted(set(paths), key=lambda p: (len(Path(p).parts), p)):
        rel = safe_rel(rel)
        parent = home
        saved = source
        for part in Path(rel).parts[:-1]:
            parent = parent / part
            saved = saved / part
            if parent.is_symlink() or saved.is_symlink():
                raise Failed('A folder was replaced by a link. Your current files were kept. Check the folder and try again.')
            parent.mkdir(exist_ok=True)
        src = source / rel
        if src.is_dir() and not src.is_symlink():
            directory = parent / Path(rel).name
            if directory.is_symlink():
                raise Failed('A folder was replaced by a link. Your current files were kept. Check the folder and try again.')
            if not directory.exists():
                directory.mkdir()
                made_dirs.append((src, directory))
            elif not directory.is_dir():
                raise Failed('A file is in the place of a folder. Your current files were kept. Move it and try again.')
            destinations[rel] = directory
            continue
        target = keep_both_name(parent / Path(rel).name, date, reserved)
        destinations[rel] = target
        reserved.add(target)

    # Choose every dated name before writing links: a target can sort after its link, and truncation or a
    # previous restore can change either name. Never resolve links through today's files or the staging tree.
    def reference_parts(parent, link):
        if not os.path.isabs(link):
            return parent + link.split('/')
        saved_home = Path(snapshot_home) if snapshot_home is not None else home
        parts = deque(link.split('/'))
        # Match the known Home prefix while allowing redundant separators and dots. Leave the
        # remaining components untouched: '..' must still wait for intermediate directory links.
        for part in saved_home.parts[1:]:
            while parts and parts[0] in ('', '.'):
                parts.popleft()
            if not parts or parts.popleft() != part:
                return None
        return list(parts)

    def link_destination(rel, link):
        parts = reference_parts(list(Path(rel).parts[:-1]), link)
        if parts is None:
            return None
        pending, resolved, expansions = deque(parts), [], 0
        while pending:
            part = pending.popleft()
            if part in ('', '.'):
                continue
            if part == '..':
                if not resolved:  # outside the backed-up Home: keep the original link
                    return None
                resolved.pop()
                continue
            ref = '/'.join(resolved + [part])
            if not pending:
                # Keep a final selected link as a link, including chains and self-links.
                return destinations.get(ref)
            src = source / ref
            if ref in destinations and src.is_symlink():
                # Expand directory links before processing '..'. Bound expansions, not path strings:
                # loop -> loop/sub grows forever without ever repeating the whole reference.
                expansions += 1
                if expansions > 40:
                    return None
                target_parts = reference_parts(resolved, os.readlink(src))
                if target_parts is None:
                    return None
                pending.extendleft(reversed(target_parts))
                resolved = []
            elif src.is_symlink() or not src.is_dir():
                # A missing or non-directory prefix cannot be canceled by a later '..'.
                return None
            else:
                resolved.append(part)
        return destinations.get('/'.join(resolved) or '.')

    for rel, target in destinations.items():
        src = source / rel
        if src.is_dir() and not src.is_symlink():
            continue
        if src.is_symlink():
            link = os.readlink(src)
            restored_target = link_destination(rel, link)
            if restored_target is not None:
                link = str(restored_target) if os.path.isabs(link) else os.path.relpath(restored_target, target.parent)
            target.symlink_to(link)
        else:
            with src.open('rb') as stream, target.open('xb') as dst:
                shutil.copyfileobj(stream, dst)
        shutil.copystat(src, target, follow_symlinks=False)
    # Apply saved folder permissions after writing children; never change an existing folder's permissions.
    for src, directory in reversed(made_dirs):
        shutil.copystat(src, directory, follow_symlinks=False)


def restore_start(snap, where, paths, mode="keep"):
    if mode not in ("keep", "replace", "both"):
        raise Failed("Choose whether to keep, replace, or keep both copies.")
    if not SNAP_ID.match(snap):
        raise Failed("That isn't a backup on the drive.")
    if where != "home":
        if not Path(where).is_absolute() or not Path(where).is_dir():
            raise Failed("Choose a folder on this computer to restore into.")
    paths = [safe_rel(p) for p in paths]
    if jread(RESTORED, {}).get("running") and pid_alive(jread(RESTORED, {}).get("pid")):
        raise Failed("A restore is running already. Wait for it to finish.")
    args = [str(Path(__file__).resolve()), "restore", snap, where, "--mode", mode, *paths]
    r = run(["systemd-run", "--user", "--collect", "--quiet", "--unit", f"starchaser-backup-restore-{os.getpid()}", "--", *args], timeout=30)
    if r.returncode:                    # no user manager: its own session, so closing Settings doesn't stop it
        subprocess.Popen(args, start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return {"ok": True}


def restore(snap, where, paths, mode="keep"):
    """The restore itself: home puts files back where they were (keeping any that are newer on this computer),
    a folder gets a new folder of its own inside it (nothing in it can be replaced)."""
    jwrite(RESTORED, {"running": True, "pid": os.getpid(), "started": time.time()})
    mounted_now, conf = False, jread(CONFIG, {})
    staging = None
    try:
        if mode not in ("keep", "replace", "both"):
            raise Failed("Choose whether to keep, replace, or keep both copies.")
        paths = [safe_rel(p) for p in paths]
        repo, password, mounted_now = open_drive(conf)
        root = snapshot_root(repo, password, snap)
        both = where == "home" and mode == "both"
        in_place = where == "home" and not both
        if both:
            staging = tempfile.TemporaryDirectory(prefix='starchaser-restore-')
        target = Path(staging.name) if both else HOME if in_place else new_folder(where)
        r, _, _ = restic(repo, password, "ls", "--json", "--no-lock", "--recursive", snap,
                         *([f"{root}/{p}" for p in paths] or [root]), timeout=3600)
        if r.returncode:
            raise Failed(restic_error(r))
        nodes = list({n["path"]: n for n in ls_nodes(r.stdout)
                      if n.get("type") in ("file", "symlink", "dir") and n["path"].rstrip('/') != root.rstrip('/')}.values())
        if not nodes:
            raise Failed("Those files aren't in that backup.")
        kept = newer_on_disk(nodes, root, target) if in_place and mode == "keep" else []
        if not in_place and not both:
            target.mkdir(mode=0o700)
        # snapshot:folder restores the backed-up Home folder's contents, so they land in this Home (or the new
        # folder) however the account was named on the computer that made the backup; --include is relative to it
        includes = [x for p in paths for x in ("--include", "/" + re.sub(r"([\\[*?])", r"\\\1", p))]
        r, _, _ = restic(repo, password, "restore", f"{snap}:{root}", "--json", "--verbose=2", "--target", str(target),
                         "--overwrite", ("always" if mode == "replace" else "if-newer") if in_place else "never", *includes, timeout=24 * 3600)
        if r.returncode:
            raise Failed(restic_error(r))
        events = [json.loads(line) for line in r.stdout.splitlines() if line.strip()]
        summaries = [m for m in events if m.get("message_type") == "summary"]
        if len(summaries) != 1:
            raise Failed("The restore couldn't be confirmed. Check the files and try again.")
        summary = summaries[0]
        restored_items = int(summary.get("files_restored") or 0)
        skipped_items = int(summary.get("files_skipped") or 0)
        completed = {m.get("item"): m.get("action") for m in events
                     if m.get("message_type") == "verbose_status" and m.get("action") in ("restored", "updated", "unchanged")}
        expected = {"/" + n["path"][len(root):].lstrip("/") for n in nodes}
        # restic counts directories too. Verify its summary against completion
        # events, then count only requested files for the person's message.
        actual_files = {p for p in completed if p in expected}
        if (restored_items + skipped_items < len(nodes) or actual_files != expected
                or len(completed) != restored_items + skipped_items):
            raise Failed("The restore didn't match the files you chose. Check the files and try again.")
        files = {"/" + n["path"][len(root):].lstrip("/") for n in nodes if n["type"] != "dir"}
        restored = sum(completed[p] != "unchanged" for p in files)
        folders = sum(completed[p] != "unchanged" for p in expected - files)
        unchanged = len(files) - restored - len(kept)
        if both:
            r, _, _ = restic(repo, password, 'snapshots', snap, '--json', '--no-lock')
            if r.returncode:
                raise Failed(restic_error(r))
            date = datetime.fromtimestamp(stamp(json.loads(r.stdout)[0]['time'])).strftime('%b %-d, %-I:%M %p')
            place_both(target, HOME, [p.lstrip('/') for p in expected], date, snapshot_home=root)
            target = HOME
        message = restored_message(restored, in_place, target, kept, unchanged=unchanged, both=both, folders=folders)
        result = {"running": False, "ok": True, "message": message, "folder": str(target), "kept": kept[:50], "keptCount": len(kept)}
    except (Failed, OSError, ValueError, TypeError) as e:
        result = {"running": False, "ok": False, "message": str(e) if isinstance(e, Failed) else "The restore couldn't be confirmed. Check the files and try again."}
    finally:
        if staging is not None:
            staging.cleanup()
        put_away(conf.get("uuid", ""), mounted_now, running())
    result["finished"] = time.time()
    jwrite(RESTORED, result)
    notify("Restore finished" if result["ok"] else "Restore didn't finish", result["message"], low=result["ok"])
    return result


def restored_message(restored, home, target, kept, unchanged=0, both=False, folders=0):
    if restored == 0 and folders:
        text = f'Restored {folders:,} folder{"" if folders == 1 else "s"}.'
    elif restored == 0:
        text = 'Nothing was restored.'
    elif both:
        text = f"Restored {restored:,} file{'' if restored == 1 else 's'} next to the current {'one' if restored == 1 else 'ones'}."
    elif home:
        text = f"Restored {restored:,} file{'' if restored == 1 else 's'}."
    else:
        parent = 'your Home folder' if Path(target).parent == HOME else f'"{Path(target).parent.name}"'
        text = f'Restored {restored:,} file{"" if restored == 1 else "s"} to "{Path(target).name}" in {parent}.'
    if kept:
        names = ', '.join(Path(p).name for p in kept[:3]) + ('…' if len(kept) > 3 else '')
        text += (' ' + names + ' is newer on this computer than in the backup, so it was kept.' if len(kept) == 1 else
                 f' {len(kept):,} files are newer on this computer than in the backup, so they were kept: {names}.')
        text += ' To get the older version, choose Replace with backup or Keep both.'
    if unchanged > 0:
        text += f' {unchanged:,} other file{" was" if unchanged == 1 else "s were"} already the same.'
    return text


# ---------------------------------------------------------------- the command line

def change_password(answer):
    new = str(answer.get('new') or '')
    if len(new) < 8 or new != answer.get('repeat') or '\n' in new or '\0' in new:
        raise Failed('Type the same backup password twice, with at least 8 characters.')
    conf = jread(CONFIG, {})
    if not conf.get('encrypted'):
        raise Failed('Choose password-protected backups first.')
    mounted_now = False
    try:
        repo, current, mounted_now = open_drive(conf)
        runtime = os.environ.get('XDG_RUNTIME_DIR')
        with tempfile.TemporaryDirectory(prefix='starchaser-backup-key-', dir=runtime if runtime and Path(runtime).is_dir() else None) as temp:
            path = Path(temp) / 'new-password'
            with open(path, 'x', opener=lambda name, flags: os.open(name, flags, 0o600)) as stream:
                stream.write(new)
            result, _, _ = restic(repo, current, 'key', 'passwd', '--new-password-file', str(path), timeout=120)
            if result.returncode:
                raise Failed("The backup password didn't change. Keep your current password. " + restic_error(result))
        if not keyring_set(conf['uuid'], conf.get('name') or 'Backups', new):
            raise Failed("The new backup password is active, but couldn't be saved for automatic backups. Keep the new password and choose these backups again in Settings.")
        try:
            write_conf(dict(conf, passwordMade=time.time()))
        except OSError:
            return {'ok': True, 'message': "The new backup password is active and saved for automatic backups. Its date couldn't be saved. Write the new password on your recovery sheet."}
        return {'ok': True, 'message': 'The backup password was changed. Write the new password on your recovery sheet.'}
    finally:
        put_away(conf.get('uuid', ''), mounted_now, running() or restoring())


def backup_computers():
    result = run(['starchaser', 'fleet', 'list'], timeout=30)
    try:
        machines = json.loads(result.stdout).get('machines', []) if result.returncode == 0 else []
    except ValueError:
        machines = []
    rows = []
    for machine in machines:
        user, host = machine.get('user') or '', machine.get('ip') or ''
        if not machine.get('starchaser') or not re.fullmatch(r'[a-z_][a-z0-9_-]{0,31}', user) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]*', host):
            continue
        port = int(machine.get('port') or 22)
        if not 1 <= port <= 65535:
            continue
        computer = re.sub(r'[^A-Za-z0-9_.-]', '-', os.uname().nodename)
        folder = '/home/' + user + '/Starchaser-Backups/' + computer + '-' + HOME.name
        address = 'sftp:' + user + '@' + host + ':' + folder if port == 22 else 'sftp://' + user + '@' + host + ':' + str(port) + '/' + folder
        rows.append({'id': machine['id'], 'name': machine.get('name') or machine.get('hostname') or host,
                     'location': network_location(address)})
    return {'ok': True, 'computers': rows}


def network_flags(repo):
    return ['-o', 'sftp.args=-oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=15'] if str(repo).startswith('sftp:') else []


def network_location(location):
    if re.fullmatch(r'sftp://[A-Za-z_][A-Za-z0-9_.-]*@[A-Za-z0-9][A-Za-z0-9.-]*:[0-9]{1,5}//[A-Za-z0-9_./-]+', location) and '..' not in location.split('/'):
        return location
    if re.fullmatch(r'sftp:[A-Za-z_][A-Za-z0-9_.-]*@[A-Za-z0-9][A-Za-z0-9.-]*:/[A-Za-z0-9_./-]+', location):
        if '..' not in Path(location.split(':', 2)[2]).parts:
            return location
    path = Path(location)
    if not path.is_absolute() or not path.is_dir() or path.is_symlink():
        raise Failed("Choose a mounted network folder or an SFTP address such as sftp:alex@backup-box:/backups/alex. Passwords don't belong in the address.")
    result = run(['findmnt', '-J', '-T', str(path), '-o', 'FSTYPE,TARGET,SOURCE'])
    try:
        mount_info = json.loads(result.stdout)['filesystems'][0]
    except (ValueError, KeyError, IndexError):
        raise Failed("This folder isn't on a connected network drive.") from None
    if mount_info.get('fstype') not in ('nfs', 'nfs4', 'cifs', 'smb3', 'fuse.sshfs'):
        raise Failed("This folder isn't on a connected network drive. Connect it in Files first.")
    return str(path)


def use_network(location, answer):
    if not all(restic_version()):
        raise Failed(NO_TOOL)
    location = network_location(location)
    password = str(answer.get('password') or '')
    if answer.get('create') is True and password != answer.get('repeat'):
        raise Failed('Type the same new backup password twice before creating network backups.')
    if len(password) < 8:
        raise Failed('Protect network backups with a password of at least 8 characters.')
    uuid = 'network-' + hashlib.sha256(location.encode()).hexdigest()[:32]
    result, _, _ = restic(location, password, 'cat', 'config', '--no-lock', timeout=120)
    if result.returncode:
        # A failed open could mean a wrong password, permissions or an offline server.
        # Creation must be requested explicitly; restic init itself refuses an existing repo.
        if answer.get('create') is not True:
            raise Failed("The network backups couldn't be opened. Check the password and connection. To start new backups, choose Create new backups.")
        result, _, _ = restic(location, password, 'init', timeout=120)
        if result.returncode:
            raise Failed("Network backups couldn't be created. Check the address, connection and access. Existing backups were kept.")
    identity = repo_id(location, password)
    if not keyring_set(uuid, 'Network backups', password):
        raise Failed("The backup password couldn't be saved. Existing backup settings were kept.")
    old = jread(CONFIG, {})
    write_conf({'uuid': uuid, 'network': location, 'name': 'Network backups', 'encrypted': True, 'repoId': identity,
                'schedule': old.get('schedule', 'daily'), 'since': time.time(), 'skipVms': old.get('skipVms', True)})
    if old.get('uuid') and old['uuid'] != uuid:
        forget_drive(old)
    if old.get('repoId') != identity:
        update_state(last=0, checked=0, pruned=0, used=None, error='')
    arm(uuid)
    start()
    return {'ok': True, 'name': 'Network backups'}


def app_manifest():
    packages = run(['pacman', '-Qqe'], timeout=60)
    flatpaks = run(['flatpak', 'list', '--app', '--columns=application'], timeout=60)
    path = STATE_DIR / 'backup-apps.json'
    jwrite(path, {'version': 1, 'computer': os.uname().nodename, 'time': time.time(),
                  'packages': packages.stdout.splitlines() if packages.returncode == 0 else [],
                  'flatpaks': flatpaks.stdout.splitlines() if flatpaks.returncode == 0 else [],
                  'packagesChecked': packages.returncode == 0, 'flatpaksChecked': flatpaks.returncode == 0})
    return path


def offer():
    health = jread(HEALTH, {})
    state = jread(STATE, {})
    if health.get('state') == 'warning' and health.get('checked') and state.get('healthWarned') != health['checked']:
        notify('Back up now', health.get('message') or "This computer's drive is showing signs of wear. Open Settings > Backups.", low=False, seconds=20)
        update_state(healthWarned=health['checked'])
    return {'ok': True}


def main(argv):
    safe_streams()
    if argv[:1] in (["-h"], ["--help"], ["help"]):
        print(__doc__.strip())
        return 0
    if not argv or argv[0] not in {**COMMANDS, **INTERNAL}:
        return usage_error(PROG, f"unknown command {argv[0]!r}" if argv else "missing command", "COMMAND [ARG ...]", list(COMMANDS))
    cmd, rest = argv[0], argv[1:]
    sizes = {"computers": (0, 0), "password": (0, 0), "offer": (0, 0), "network": (1, 1), "status": (0, 0), "drives": (0, 0), "use": (1, 1), "set": (2, 2), "start": (0, 0), "stop-using": (0, 0),
             "snapshots": (0, 0), "files": (1, 2), "preview": (2, 2), "restore-plan": (1, 999), "restore-start": (2, 999), "restore": (2, 999), "run": (0, 1)}[cmd]
    if not sizes[0] <= len(rest) <= sizes[1] or (cmd == "run" and rest not in ([], ["--auto"])):
        return usage_error(PROG, f"wrong arguments for {cmd!r}", {**COMMANDS, **INTERNAL}[cmd])
    mode = "keep"
    if cmd in ("restore", "restore-start") and len(rest) >= 4 and rest[2] == "--mode":
        mode, rest = rest[3], rest[:2] + rest[4:]
    try:
        if cmd in ("use", "network", "password"):
            try:
                answer = json.loads(sys.stdin.read() or "{}")
            except ValueError:
                answer = {}
            result = change_password(answer) if cmd == "password" else (use_network if cmd == "network" else use)(rest[0], answer if isinstance(answer, dict) else {})
        elif cmd == "drives":
            result = {"ok": True, "drives": drives()}
        elif cmd == "run":
            result = backup(auto=rest == ["--auto"])
        else:
            result = {"computers": backup_computers, "offer": offer, "status": status, "set": set_option, "start": start, "stop-using": stop_using, "snapshots": snapshots,
                      "files": files, "preview": preview, "restore-plan": lambda s, *p: restore_plan(s, list(p)), "restore-start": lambda s, w, *p: restore_start(s, w, list(p), mode),
                      "restore": lambda s, w, *p: restore(s, w, list(p), mode)}[cmd](*rest)
    except Failed as e:
        print(json.dumps({"ok": False, "errors": str(e)}))
        return 1
    print(json.dumps(result))
    return 0 if result.get("ok") else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
