#!/usr/bin/env python3
"""Install apps described by a coreapp.toml on this Federated Core.

Runs on the Core as root (coreapp-dev puts it in /opt/coreapps). An app is
a coreapp.toml, an icon.png and an image: the app's repository has no
scripts or compose file of its own. This program checks the manifest and
makes the Core's generic app format (/federated/services/<name>/) from its
own templates, so what an app can do on the Core is decided here, not by
whoever wrote the app.

coreapps manifest <dir>              check <dir>/coreapp.toml, print its values
coreapps plan [--downgrade] <source> what install would do on this Core
coreapps install [--addon-ok] [--recreate] [--downgrade] [--drop-database] <source>
                                     install the app, or update it
                                     (--recreate: a new container even if
                                     nothing changed; --downgrade: allow an
                                     older release than the installed one;
                                     --drop-database: allow dropping
                                     "postgres" or "mysql" from needs,
                                     deleting its database)
coreapps update [--addon-ok] <name>  update an app installed from a
                                     repository to its newest release
coreapps remove <name>               uninstall an app installed by coreapps
coreapps list                        the apps installed by coreapps
coreapps login <host>[/<owner>] <user>
                                     keep a token (read from stdin) for
                                     installing private apps from host
                                     (with /<owner>: that owner's apps only,
                                     used before the host's token)
coreapps logout <host>[/<owner>]     forget that token
coreapps logins                      the hosts this Core has tokens for
coreapps mail <name>                 what the Core's mail server did with the
                                     mail the app sent in the last day
coreapps core                        what this Core offers apps: its services
                                     and their versions, and the machine
coreapps test-account [--remove]     make (or refresh, with the password on
                                     stdin) the person coreapp signin signs
                                     in with, or remove it (with its mailbox)
coreapps test-inbox [--clear]        the newest mail in the test account's
                                     mailbox (or empty it)

<source> is a folder with coreapp.toml (and icon.png), or a git
repository: https://host/owner/repo[@tag]. A private repository, and a
private image, need a token for their host (coreapps login): a Gitea token
with read access to repositories and packages. From a repository, only
coreapp.toml and icon.png are read, at the tag (default: the newest
release tag, v1.2.3), whose version must match; the image is pulled from
its registry.

`manifest` also works off the Core. install exits with 3 if this Core's
tier would record the app as a billable add-on and --addon-ok isn't given.
"""

import base64
import email.parser
import email.policy
import glob
import html.parser
import json
import os
import re
import shutil
import struct
import subprocess
import sys
import tempfile
import time
import tomllib
import urllib.error
import urllib.parse
import urllib.request

HERE = os.path.dirname(os.path.realpath(__file__))
TEMPLATES = os.path.join(HERE, "templates")
NEEDS_DIR = os.path.join(HERE, "needs")
FEDERATED = "/federated"
SERVICES = FEDERATED + "/services"
APPS = FEDERATED + "/apps"
LOGS = FEDERATED + "/logs/coreapps"
# Marks a services folder as made by coreapps (and holds what it set up)
MARKER = ".coreapp"
# Addresses for apps: 192.168.5.0/24, which Federated set aside for them
# (all in the core network's 192.168.0.0/16; Federated's apps are in
# 192.168.0.x)
PREFIX = "192.168.5."
FIRST, LAST = 2, 254
# Hostnames on the Core that aren't apps in /federated/services or lib
RESERVED = {"www", "mail", "ns1", "ns2", "autodiscover", "autoconfig",
            "panel", "dashboard", "mcphub", "api", "admin"}
# What an app can ask for, in the order they're set up
NEEDS = ["postgres", "mysql", "sso", "email"]

# What coreapp.toml may contain. Values end up in shell-sourced and YAML
# files on the Core, so each is limited to characters that are safe there.
FIELDS = {
    "name": r"[a-z](?:[a-z0-9-]{0,29}[a-z0-9])",
    "title": r"[A-Za-z0-9][A-Za-z0-9 .,!?()&+_-]{0,39}",
    "description": r"[^\"$`\\@\x00-\x1f\x7f]{0,200}",
    "version": r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}",
    # The registry is part of the name (localhost/... for images that only
    # exist on this Core), so it's never Docker Hub by accident
    "image": (r"(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+)(?::[0-9]{1,5})?"
              r"(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+"),
    "port": None,
    "health": r"/[A-Za-z0-9._~/-]{0,100}",
    "docs": r"(?:https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~/%+-]*)?)?",
    "needs": None,
    "sso": None,
    "postgres": None,
    "mysql": None,
}
REQUIRED = ["name", "title", "version", "image", "port"]

# [sso]: how the app's OpenID Connect client in Authelia differs from the
# default, for apps whose sign-in can't be configured to match it
SSO_DEFAULTS = {"callback": "/auth/callback", "pkce": True,
                "token_auth": "client_secret_basic"}
SSO_CALLBACK = r"/[A-Za-z0-9._~/-]{0,200}"
SSO_TOKEN_AUTH = ["client_secret_basic", "client_secret_post"]

# [postgres] and [mysql]: the oldest server version the app works with
# (the installer refuses an older Core), and for postgres the extensions
# the Core's superuser makes in the app's database (ones the app's own user
# can't, like vector)
DB_SETTINGS = {"postgres": ["min_version", "extensions"], "mysql": ["min_version"]}
DB_SERVER = {"postgres": "PostgreSQL", "mysql": "MariaDB"}
MIN_VERSION = r"[0-9]{1,4}(?:\.[0-9]{1,4}){0,2}"
EXTENSION = r"[a-z0-9][a-z0-9_-]{0,62}"

# Repositories apps are installed from: https only, no user or password in
# the URL. Tags: v + a version; releases (picked by default) are numeric.
REPO_URL = r"https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._-]+){2,}?(?:\.git)?/?"
TAG = r"v[A-Za-z0-9][A-Za-z0-9._-]{0,63}"
RELEASE_TAG = r"v[0-9]+(?:\.[0-9]+)*"
# git for untrusted repositories: https only, never asks for a password,
# ignores the system's and root's git settings
GIT_ENV = {"PATH": "/usr/bin:/bin", "GIT_TERMINAL_PROMPT": "0",
           "GIT_ALLOW_PROTOCOL": "https", "GIT_CONFIG_NOSYSTEM": "1",
           "GIT_CONFIG_GLOBAL": "/dev/null", "HOME": "/nonexistent",
           "LC_ALL": "C"}
GIT_TIMEOUT = 120
# Tokens for private repositories and registries (root only), by host, or
# by host/owner for one account or organization's apps on a host where
# others need another token
CREDENTIALS = "/etc/coreapps/credentials"
HOST = r"[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[0-9]{1,5})?"
LOGIN_USER = r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}"
OWNER = r"[a-z0-9][a-z0-9._-]{0,63}"
LOGIN_KEY = HOST + r"(?:/" + OWNER + r")?"
TOKEN = r"[A-Za-z0-9._~+/=-]{8,512}"


class Refused(Exception):
    """The app can't be installed as it is; the message says why."""


def say(*args):
    print(*args, flush=True)


# --- coreapp.toml -------------------------------------------------------------

def read_sso(value):
    """coreapp.toml's [sso] table, checked, with defaults filled in."""
    if not isinstance(value, dict):
        raise Refused("coreapp.toml: sso must be a table: [sso] with callback, pkce, token_auth.")
    unknown = sorted(set(value) - set(SSO_DEFAULTS))
    if unknown:
        raise Refused(f"coreapp.toml: [sso]: unknown setting(s) {', '.join(unknown)} "
                      f"(it knows {', '.join(SSO_DEFAULTS)}).")
    sso = dict(SSO_DEFAULTS, **value)
    if not isinstance(sso["callback"], str) or not re.fullmatch(SSO_CALLBACK, sso["callback"]):
        raise Refused(f"coreapp.toml: [sso] callback = {sso['callback']!r} isn't allowed: "
                      "a path on the app's own address, like \"/auth/callback\".")
    if not isinstance(sso["pkce"], bool):
        raise Refused("coreapp.toml: [sso] pkce must be true or false.")
    if sso["token_auth"] not in SSO_TOKEN_AUTH:
        raise Refused(f"coreapp.toml: [sso] token_auth must be {' or '.join(SSO_TOKEN_AUTH)}.")
    return sso


def read_database(need, value):
    """coreapp.toml's [postgres] or [mysql] table, checked."""
    known = DB_SETTINGS[need]
    if not isinstance(value, dict):
        raise Refused(f"coreapp.toml: {need} must be a table: [{need}] with {', '.join(known)}.")
    unknown = sorted(set(value) - set(known))
    if unknown:
        raise Refused(f"coreapp.toml: [{need}]: unknown setting(s) {', '.join(unknown)} "
                      f"(it knows {', '.join(known)}).")
    db = {"min_version": "", "extensions": []}
    if "min_version" in value:
        version = value["min_version"]
        if isinstance(version, int) and not isinstance(version, bool):
            version = str(version)
        if not isinstance(version, str) or not re.fullmatch(MIN_VERSION, version):
            raise Refused(f'coreapp.toml: [{need}] min_version must be a {DB_SERVER[need]} '
                          'version, like min_version = "18" or "17.4".')
        db["min_version"] = version
    extensions = value.get("extensions", [])
    if not isinstance(extensions, list) or not all(
            isinstance(e, str) and re.fullmatch(EXTENSION, e) for e in extensions):
        raise Refused('coreapp.toml: [postgres] extensions must be a list of extension names, '
                      'like extensions = ["vector"].')
    db["extensions"] = sorted(set(extensions))
    return db


def read_manifest(folder):
    """coreapp.toml in folder, checked, with defaults filled in."""
    path = os.path.join(folder, "coreapp.toml")
    if os.path.islink(path):
        raise Refused("coreapp.toml is a symbolic link; it has to be a file.")
    try:
        with open(path, "rb") as f:
            data = tomllib.load(f)
    except FileNotFoundError:
        raise Refused(f"No coreapp.toml in {folder}.")
    except tomllib.TOMLDecodeError as e:
        raise Refused(f"coreapp.toml isn't valid TOML: {e}")

    unknown = sorted(set(data) - set(FIELDS))
    if unknown:
        raise Refused(f"coreapp.toml: unknown setting(s) {', '.join(unknown)} "
                      f"(it knows {', '.join(FIELDS)}).")
    missing = [k for k in REQUIRED if k not in data]
    if missing:
        raise Refused(f"coreapp.toml needs {', '.join(missing)}.")

    m = {"description": "", "health": "/", "docs": "", "needs": [], "sso": dict(SSO_DEFAULTS),
         "postgres": {"min_version": "", "extensions": []},
         "mysql": {"min_version": "", "extensions": []}}
    for key, value in data.items():
        if key == "port":
            if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= 65535:
                raise Refused("coreapp.toml: port must be a number from 1 to 65535.")
        elif key == "needs":
            if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
                raise Refused('coreapp.toml: needs must be a list, like needs = ["postgres", "sso"].')
            bad = [v for v in value if v not in NEEDS]
            if bad:
                raise Refused(f"coreapp.toml: needs: unknown {', '.join(bad)} "
                              f"(it knows {', '.join(NEEDS)}).")
            value = [n for n in NEEDS if n in value]
            if "postgres" in value and "mysql" in value:
                raise Refused("coreapp.toml: needs: postgres or mysql, not both "
                              "(both give the app DB_* settings).")
        elif key == "sso":
            value = read_sso(value)
        elif key in DB_SETTINGS:
            value = read_database(key, value)
        else:
            if not isinstance(value, str) or not re.fullmatch(FIELDS[key], value):
                raise Refused(f"coreapp.toml: {key} = {value!r} isn't allowed. "
                              + HINTS.get(key, ""))
        m[key] = value
    if "sso" in data and "sso" not in m["needs"]:
        raise Refused('coreapp.toml: [sso] is for apps with "sso" in needs.')
    for need in DB_SETTINGS:
        if need in data and need not in m["needs"]:
            raise Refused(f'coreapp.toml: [{need}] is for apps with "{need}" in needs.')
    if m["name"] in RESERVED:
        raise Refused(f"'{m['name']}' is one of the Core's own hostnames. Pick another name.")
    m["dbname"] = "coreapp_" + m["name"].replace("-", "_")
    return m


HINTS = {
    "name": "Use 2-31 lowercase letters, digits and -, starting with a letter "
            "and not ending with -. It becomes https://<name>.<domain>.",
    "title": "Up to 40 letters, digits, spaces and . , ! ? ( ) & + _ -",
    "description": "Up to 200 characters, without \" $ ` \\ @ or line breaks.",
    "version": "Letters, digits, . _ and - (it's the image's tag).",
    "image": "Include the registry: localhost/coreapp/<name> for an image you "
             "copy to the Core, or e.g. gitea.example.com/owner/<name>.",
    "health": "A path, like /health.",
    "docs": "An https:// address.",
}


# --- This Core ------------------------------------------------------------------

def run(cmd, **kw):
    return subprocess.run(cmd, text=True, capture_output=True, **kw)


def federated_settings():
    """/etc/federated's values (it's shell, so let bash read it)."""
    out = run(["bash", "-c", '. /etc/federated; echo "$DOMAIN"; echo "$TIER"'])
    if out.returncode != 0:
        raise Refused("This isn't a Federated Core (no /etc/federated).")
    domain, tier = (out.stdout.splitlines() + ["", ""])[:2]
    return domain, tier


def service_value(path, key):
    """A value from a generic app's service file, without running it."""
    try:
        with open(path) as f:
            for line in f:
                m = re.match(rf'{key}=(["\']?)(.*)\1\s*$', line.strip())
                if m:
                    return m.group(2)
    except OSError:
        pass
    return ""


def is_ours(name):
    folder = os.path.join(SERVICES, name)
    if os.path.exists(os.path.join(folder, MARKER)):
        return True
    return False


def marker_needs(name):
    """What coreapps set up for an installed app (from its marker)."""
    folder = os.path.join(SERVICES, name)
    try:
        with open(os.path.join(folder, MARKER)) as f:
            for line in f:
                if line.startswith("needs="):
                    return line.split("=", 1)[1].split()
    except OSError:
        return []
    # Folders deployed before coreapp.toml: tell from DEPENDS
    depends = service_value(os.path.join(folder, "service"), "DEPENDS").split()
    return [n for n in NEEDS if read_text(NEEDS_DIR, n, "depends").strip() in depends]


def used_addresses():
    used = set()
    out = run(["docker", "network", "inspect", "core", "-f",
               "{{range .Containers}}{{.IPv4Address}} {{end}}"])
    for cidr in out.stdout.split():
        used.add(cidr.split("/")[0])
    for name in os.listdir(SERVICES):
        ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP")
        if ip:
            used.add(ip)
    return used


def pick_address(name):
    """The app's address: the one it has, or the first free one. (Apps
    from before the range moved get a new one; updating moves them.)"""
    if is_ours(name):
        ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP")
        if ip.startswith(PREFIX):
            return ip
    used = used_addresses()
    for n in range(FIRST, LAST + 1):
        if PREFIX + str(n) not in used:
            return PREFIX + str(n)
    raise Refused(f"No free address left in {PREFIX}{FIRST}-{LAST}.")


# --- Tokens for private apps ----------------------------------------------------

def read_credentials():
    try:
        with open(CREDENTIALS, "rb") as f:
            data = tomllib.load(f)
    except FileNotFoundError:
        return {}
    except tomllib.TOMLDecodeError as e:
        raise Refused(f"{CREDENTIALS} isn't valid: {e}")
    return {key: c for key, c in data.items()
            if re.fullmatch(LOGIN_KEY, key) and isinstance(c, dict)
            and re.fullmatch(LOGIN_USER, str(c.get("user", "")))
            and re.fullmatch(TOKEN, str(c.get("token", "")))}


def write_credentials(creds):
    os.makedirs(os.path.dirname(CREDENTIALS), mode=0o700, exist_ok=True)
    os.chmod(os.path.dirname(CREDENTIALS), 0o700)
    text = ("# Tokens coreapps uses to install private apps, by host or host/owner\n"
            "# (used first for that owner's apps). Manage with coreapps login / logout.\n")
    for host in sorted(creds):
        text += f'\n["{host}"]\nuser = "{creds[host]["user"]}"\ntoken = "{creds[host]["token"]}"\n'
    new = CREDENTIALS + ".new"
    fd = os.open(new, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        f.write(text)
    os.rename(new, CREDENTIALS)


def basic_auth(host, owner=""):
    """(the login's key, 'user:token' in base64) for owner's apps on host:
    host/owner's token, else host's; or (None, None)."""
    creds = read_credentials()
    for key in ([f"{host}/{owner.lower()}"] if owner else []) + [host]:
        c = creds.get(key)
        if c:
            return key, base64.b64encode(f"{c['user']}:{c['token']}".encode()).decode()
    return None, None


def login_key(arg):
    """host or host/owner, checked and in lowercase."""
    key = arg.lower().rstrip("/")
    if not re.fullmatch(LOGIN_KEY, key):
        raise Refused(f"'{arg}' isn't a host name (like gitea.example.com) or a host and "
                      "owner (gitea.example.com/my-team).")
    return key


def url_host(url):
    return url.split("://", 1)[1].split("/", 1)[0].lower()


def check_token(host, user, token):
    """Whether host's registry accepts the token: True, False, or None
    (couldn't tell)."""
    auth = "Basic " + base64.b64encode(f"{user}:{token}".encode()).decode()

    def get(url):
        req = urllib.request.Request(url, headers={"Authorization": auth})
        try:
            with urllib.request.urlopen(req, timeout=15) as r:
                return r.status, r.headers
        except urllib.error.HTTPError as e:
            return e.code, e.headers
        except (urllib.error.URLError, OSError):
            return None, {}

    status, headers = get(f"https://{host}/v2/")
    if status == 200:
        return True
    challenge = (headers or {}).get("WWW-Authenticate", "")
    m = re.search(r'realm="([^"]+)"', challenge)
    if status == 401 and challenge.lower().startswith("bearer") and m:
        service = re.search(r'service="([^"]+)"', challenge)
        realm = m.group(1) + (f"?service={urllib.parse.quote(service.group(1))}" if service else "")
        status, _ = get(realm)
        if status == 200:
            return True
        if status in (401, 403):
            return False
    return False if status in (401, 403) else None


def login(arg, user):
    key = login_key(arg)
    host = key.split("/", 1)[0]
    if not re.fullmatch(LOGIN_USER, user):
        raise Refused(f"'{user}' isn't a user name.")
    token = sys.stdin.readline().strip()
    if not re.fullmatch(TOKEN, token):
        raise Refused("That isn't a token (8-512 letters, digits and . _ ~ + / = -).")
    ok = check_token(host, user, token)
    if ok is False:
        raise Refused(f"{host} rejected the token for {user}. Nothing was saved.")
    creds = read_credentials()
    creds[key] = {"user": user, "token": token}
    write_credentials(creds)
    say(f"Saved a token for {user}@{host}"
        + (f", for {key.split('/', 1)[1]}'s apps there" if "/" in key else "")
        + (" (its registry accepts it)." if ok else " (couldn't check it with its registry)."))
    return 0


def logout(arg):
    key = login_key(arg)
    creds = read_credentials()
    if creds.pop(key, None) is None:
        say(f"No token for {key}.")
        return 0
    write_credentials(creds)
    say(f"Forgot the token for {key}.")
    return 0


def list_logins():
    creds = read_credentials()
    if not creds:
        say("No tokens: this Core installs public apps only.")
    for key in sorted(creds):
        say(f"{key}  (user {creds[key]['user']}"
            + (f"; for {key.split('/', 1)[1]}'s apps)" if "/" in key else ")"))
    return 0


# --- Where an app comes from: a folder or a repository ------------------------

def normalize_url(url):
    """https://Host/owner/repo.git/ -> https://host/owner/repo"""
    url = url.rstrip("/")
    if url.endswith(".git"):
        url = url[:-4]
    scheme, _, rest = url.partition("://")
    host, _, path = rest.partition("/")
    return f"{scheme}://{host.lower()}/{path}"


def is_release(tag):
    return bool(re.fullmatch(r"v[0-9]+(?:\.[0-9]+)*", tag or ""))


def version_key(tag):
    return [int(part) for part in tag[1:].split(".")]


def git(args, cwd=None, auth=None):
    """git with GIT_ENV; auth: (url prefix, base64 user:token) to send as a
    header (in the environment, so it's never in a URL or an error)."""
    env = dict(GIT_ENV)
    if auth:
        env.update({"GIT_CONFIG_COUNT": "1",
                    "GIT_CONFIG_KEY_0": f"http.{auth[0]}/.extraHeader",
                    "GIT_CONFIG_VALUE_0": f"Authorization: Basic {auth[1]}"})
    try:
        out = subprocess.run(["git", *args], cwd=cwd, env=env, capture_output=True,
                             timeout=GIT_TIMEOUT)
    except subprocess.TimeoutExpired:
        raise Refused(f"git {args[0]} took longer than {GIT_TIMEOUT} s.")
    return out


def git_blob(folder, commit, path, limit, auth=None):
    """A regular file's bytes at commit, or None if it isn't one (missing,
    a link, a folder) or is bigger than limit. (Fetched on demand, so it may
    need the repository's token.)"""
    out = git(["ls-tree", commit, "--", path], cwd=folder, auth=auth)
    fields = out.stdout.decode().split()
    if out.returncode != 0 or len(fields) < 3 or fields[0] != "100644" or fields[1] != "blob":
        return None
    size = git(["cat-file", "-s", fields[2]], cwd=folder, auth=auth)
    if size.returncode != 0 or int(size.stdout or 0) > limit:
        return None
    blob = git(["cat-file", "blob", fields[2]], cwd=folder, auth=auth)
    return blob.stdout if blob.returncode == 0 else None


def fetch_repo(arg, staging):
    """coreapp.toml and icon.png from a repository at a tag, into staging.
    Returns the source's details."""
    url, _, tag = arg.partition("@")
    if not re.fullmatch(REPO_URL, url):
        raise Refused(f"'{url}' isn't a repository address coreapps installs from: "
                      "https://host/owner/repo (no user or password in it).")
    url = normalize_url(url)
    host = url_host(url)
    owner = url.split("://", 1)[1].split("/")[1]
    key, token = basic_auth(host, owner)
    # git sends it only under the login's address: the owner's (as the URL
    # spells it; git compares paths exactly), or the host's
    auth = ((f"https://{host}/{owner}" if "/" in key else f"https://{host}"), token) \
        if token else None
    no_access = (f" If it's private, give this Core a token for {host}: coreapp login {host} "
                 f"(or coreapp login {host}/{owner.lower()} for {owner}'s apps only)."
                 if not token else
                 f" (It used the token for {key}: check it can read this repository.)")
    if tag and not re.fullmatch(TAG, tag):
        raise Refused(f"'{tag}' isn't a release tag (v and a version, like v1.2.0).")
    if not tag:
        out = git(["ls-remote", "--tags", "--refs", url], auth=auth)
        if out.returncode != 0:
            raise Refused(f"Couldn't read {url}: {out.stderr.decode().strip() or 'no answer'}."
                          + no_access)
        tags = [line.split("refs/tags/", 1)[1] for line in out.stdout.decode().splitlines()
                if "refs/tags/" in line]
        releases = [t for t in tags if re.fullmatch(RELEASE_TAG, t)]
        if not releases:
            raise Refused(f"{url} has no release tags (like v1.2.0). Publish a release "
                          "(coreapp publish tags it), or name a tag: <url>@<tag>.")
        tag = max(releases, key=version_key)
    git(["init", "-q", "--bare", staging + "/git"])
    out = git(["fetch", "-q", "--depth", "1", "--filter=blob:none", "--no-tags", url,
               f"refs/tags/{tag}"], cwd=staging + "/git", auth=auth)
    if out.returncode != 0:
        raise Refused(f"Couldn't fetch {tag} from {url}: {out.stderr.decode().strip()}"
                      + no_access)
    commit = git(["rev-parse", "FETCH_HEAD^{commit}"], cwd=staging + "/git").stdout.decode().strip()
    manifest = git_blob(staging + "/git", commit, "coreapp.toml", 64 * 1024, auth)
    if manifest is None:
        raise Refused(f"{url} has no coreapp.toml (a file, up to 64 KB) at {tag}.")
    with open(os.path.join(staging, "coreapp.toml"), "wb") as f:
        f.write(manifest)
    icon = git_blob(staging + "/git", commit, "icon.png", 1024 * 1024, auth)
    if icon is not None:
        with open(os.path.join(staging, "icon.png"), "wb") as f:
            f.write(icon)
    shutil.rmtree(staging + "/git")
    return {"source": url, "tag": tag, "commit": commit}


def resolve(arg, staging):
    """The folder to read the app from, and where it came from."""
    if arg.startswith("https://"):
        return staging, fetch_repo(arg, staging)
    if not os.path.isdir(arg):
        raise Refused(f"'{arg}' is neither a folder nor an https:// repository.")
    return arg, {}


def check_release(m, origin):
    """A repository's app: its version is the tag's, its image can be pulled."""
    if not origin:
        return
    if "v" + m["version"] != origin["tag"]:
        raise Refused(f"At {origin['tag']}, coreapp.toml says version = \"{m['version']}\"; "
                      "a release's tag and version have to match.")
    if m["image"].startswith("localhost/"):
        raise Refused(f"image = \"{m['image']}\" is a local image, which can't be "
                      "installed from a repository. Publish it to a registry first "
                      "(coreapp publish).")


def marker_value(name, key):
    try:
        with open(os.path.join(SERVICES, name, MARKER)) as f:
            for line in f:
                if line.startswith(key + "="):
                    return line.split("=", 1)[1].strip()
    except OSError:
        pass
    return ""


def federated_names():
    """Names of the Core's own apps and services, installed or not: their
    folders in /federated/services and their scripts in /federated/lib."""
    names = set()
    if os.path.isdir(SERVICES):
        names |= {n for n in os.listdir(SERVICES)
                  if os.path.isdir(os.path.join(SERVICES, n)) and not is_ours(n)
                  and re.fullmatch(FIELDS["name"], n)}
    lib = os.path.join(FEDERATED, "lib")
    if os.path.isdir(lib):
        names |= {n[:-3] for n in os.listdir(lib)
                  if n.endswith(".sh") and re.fullmatch(FIELDS["name"], n[:-3])}
    return names


def plan(m, origin=None, downgrade=False, drop_database=False):
    """What installing m would do here, or Refused."""
    name = m["name"]
    domain, tier = federated_settings()
    if not domain:
        raise Refused("This Core isn't provisioned yet (no DOMAIN in /etc/federated).")
    if name in federated_names():
        state = ("installed" if os.path.isdir(os.path.join(APPS, name))
                 else "not installed, but the Core can install it")
        raise Refused(f"'{name}' is the name of one of Federated's apps on this Core ({state}). "
                      "Pick another name (coreapp core lists the names that are taken).")
    installed = os.path.isdir(os.path.join(APPS, name))
    if installed and not is_ours(name):
        raise Refused(f"/federated/apps/{name} exists but wasn't installed by coreapps.")
    p = {
        "state": "update" if installed else "new",
        "domain": domain,
        "tier": tier,
        "address": pick_address(name),
        "url": f"https://{name}.{domain}/",
    }
    p["addon"] = "yes" if p["state"] == "new" and tier.lower() != "enterprise" else "no"
    if installed:
        before = marker_needs(name)
        dropped = [n for n in before if n not in m["needs"]]
        # A database is the app's data; a sign-in client or mail account
        # can be made again
        data = [n for n in dropped if n in DUMP]
        if data and not drop_database:
            raise Refused(f"The new coreapp.toml drops {', '.join(data)}: that deletes "
                          f"{name}'s database, with everything in it. To do that, add "
                          "--drop-database (it's dropped once the new version works).")
        p["dropped_needs"] = dropped
        p["new_needs"] = [n for n in m["needs"] if n not in before]
        # Another repository's app of the same name would take over this
        # one's data, database and sign-in client
        installed_from = marker_value(name, "source")
        if origin and installed_from and installed_from != origin["source"]:
            raise Refused(f"'{name}' on this Core was installed from {installed_from}, "
                          f"not {origin['source']}. Remove it first to install this one.")
        # An older release may not understand what the newer one left in
        # its database and /data
        installed_tag = marker_value(name, "tag")
        if origin and is_release(installed_tag) and is_release(origin["tag"]) \
                and version_key(origin["tag"]) < version_key(installed_tag):
            if not downgrade:
                raise Refused(
                    f"'{name}' has {installed_tag} installed; {origin['tag']} is older, and may "
                    "not understand the data the newer version left (its database and /data). "
                    "To install it anyway, add --downgrade (if it fails to start, the update "
                    "rolls back).")
            p["downgrade_from"] = installed_tag
    else:
        p["new_needs"] = list(m["needs"])
        p["dropped_needs"] = []
    check_db_version(m)
    p["new_extensions"] = extensions_to_enable(m, p)
    for key in ("source", "tag", "commit"):
        if origin:
            p[key] = origin[key]
    return p


def db_version(need):
    """The Core's PostgreSQL or MariaDB version, like "17.6", or ""."""
    if need == "postgres":
        out = run(["docker", "exec", "postgresql", "postgres", "--version"]).stdout
        found = re.search(r"\) ([0-9][0-9.]*[0-9])", out)
    else:
        out = run(["docker", "exec", "pdnsmysql", "mariadb", "--version"]).stdout
        found = re.search(r"([0-9][0-9.]*[0-9])-MariaDB", out)
    return found.group(1) if found else ""


def check_db_version(m):
    """Refused if the app's database server here is older than its
    [postgres] or [mysql] min_version."""
    for need in DB_SETTINGS:
        wanted = m[need]["min_version"]
        if need not in m["needs"] or not wanted:
            continue
        have = db_version(need)
        if not have:
            raise Refused(f"Couldn't find this Core's {DB_SERVER[need]} version to check "
                          f"[{need}] min_version = \"{wanted}\". Is it running?")
        key = lambda v: [int(x) for x in v.split(".")]
        if key(have) < key(wanted):
            raise Refused(f"{m['title']} needs {DB_SERVER[need]} {wanted} or newer "
                          f"([{need}] min_version in coreapp.toml); this Core has {have}.")


def extensions_to_enable(m, p):
    """[postgres] extensions the app's database doesn't have yet, or Refused
    if this Core's PostgreSQL doesn't have one."""
    wanted = m["postgres"]["extensions"]
    if not wanted:
        return []
    psql = ["docker", "exec", "postgresql", "psql", "-U", "postgres", "-Atc"]
    available = run(psql + ["SELECT name FROM pg_available_extensions"]).stdout.split()
    missing = [e for e in wanted if e not in available]
    if missing:
        raise Refused(f"coreapp.toml: [postgres] extensions: this Core's PostgreSQL doesn't have "
                      f"{', '.join(missing)} (coreapp core lists the ones it has).")
    have = []
    if p["state"] == "update" and "postgres" not in p["new_needs"]:
        have = run(psql + ["SELECT extname FROM pg_extension", "-d", m["dbname"]]).stdout.split()
    return [e for e in wanted if e not in have]


# --- Making the app's files ---------------------------------------------------

def read_text(*parts):
    try:
        with open(os.path.join(*parts)) as f:
            return f.read()
    except FileNotFoundError:
        return ""


def fill(text, values):
    for key, value in values.items():
        text = text.replace("{{" + key + "}}", value)
    return text


def write(path, text, mode=0o644):
    with open(path, "w") as f:
        f.write(text)
    os.chmod(path, mode)


ICON_LIMIT = 1024 * 1024


def icon_check(folder):
    """The app's icon.png: ("ok", "missing" or "bad", a note for the
    developer or "")."""
    path = os.path.join(folder, "icon.png")
    default = "the Core shows the default icon instead"
    if os.path.islink(path):
        return "bad", f"icon.png is a link, so {default}. Make it a file."
    if not os.path.isfile(path):
        return "missing", f"No icon.png (a PNG file up to 1 MB), so {default}."
    if os.path.getsize(path) > ICON_LIMIT:
        return "bad", f"icon.png is bigger than 1 MB, so {default}."
    with open(path, "rb") as f:
        head = f.read(24)
    if head[:8] != b"\x89PNG\r\n\x1a\n" or head[12:16] != b"IHDR":
        return "bad", f"icon.png isn't a PNG, so {default}."
    width, height = struct.unpack(">II", head[16:24])
    notes = []
    if width != height:
        notes.append(f"icon.png is {width}x{height}; the dashboard shows it in a "
                     "square, so a square one looks best.")
    if min(width, height) < 80:
        notes.append(f"icon.png is small ({width}x{height}): the dashboard shows it "
                     "at 40x40 (80x80 pixels on sharp screens); 256x256 looks good.")
    return "ok", " ".join(notes)


def icon_from(folder):
    """The app's icon.png if it's usable, else the default."""
    if icon_check(folder)[0] == "ok":
        return os.path.join(folder, "icon.png")
    return os.path.join(TEMPLATES, "icon.png")


def make_service_folder(m, p, source, origin):
    """/federated/services/<name>/ in the Core's generic format, from m."""
    values = {
        "NAME": m["name"], "TITLE": m["title"], "DESCRIPTION": m["description"],
        # Without docs, Superpanel links a search of Federated's documentation
        "DOCS": m["docs"] or (origin["source"] if origin else ""), "IMAGE": m["image"], "VERSION": m["version"],
        "IP": p["address"], "PORT": str(m["port"]), "DBNAME": m["dbname"],
        "SSO_CALLBACK": m["sso"]["callback"], "SSO_TOKEN_AUTH": m["sso"]["token_auth"],
        "SSO_PKCE": ("require_pkce: true\n        pkce_challenge_method: 'S256'"
                     if m["sso"]["pkce"] else "require_pkce: false"),
        "DEPENDS": " ".join(read_text(NEEDS_DIR, n, "depends").strip() for n in m["needs"]),
        "EXTENSIONS": " ".join(m["postgres"]["extensions"]),
    }
    compose_extra = "".join(read_text(NEEDS_DIR, n, "compose") for n in m["needs"])
    compose = read_text(TEMPLATES, "docker-compose.yml.in").replace(
        "{{COMPOSE_EXTRA}}\n", compose_extra)
    env = read_text(TEMPLATES, "env.in") + "".join(
        read_text(NEEDS_DIR, n, "env.in") for n in m["needs"])

    final = os.path.join(SERVICES, m["name"])
    new = final + ".new"
    shutil.rmtree(new, ignore_errors=True)
    os.makedirs(new)
    write(os.path.join(new, "service"), fill(read_text(TEMPLATES, "service"), values))
    write(os.path.join(new, "docker-compose.yml.in"), fill(compose, values))
    write(os.path.join(new, "env.in"), fill(env, values))
    write(os.path.join(new, "install"), fill(read_text(TEMPLATES, "install"), values), 0o755)
    write(os.path.join(new, "uninstall"), fill(read_text(TEMPLATES, "uninstall"), values), 0o755)
    for need in m["needs"]:
        os.makedirs(os.path.join(new, "needs", need))
        for step in ("setup", "teardown", "update"):
            text = read_text(NEEDS_DIR, need, step)
            if text:
                write(os.path.join(new, "needs", need, step), fill(text, values))
    shutil.copyfile(icon_from(source), os.path.join(new, "icon.png"))
    shutil.copyfile(os.path.join(source, "coreapp.toml"), os.path.join(new, "coreapp.toml"))
    write(os.path.join(new, MARKER),
          "# Installed by coreapps; delete with coreapps remove\n"
          f"needs={' '.join(m['needs'])}\n"
          + "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit", "digest")
                    if origin and origin.get(key)))
    shutil.rmtree(final, ignore_errors=True)
    os.rename(new, final)


# --- install, update, remove ----------------------------------------------------

def log_path(name, what):
    os.makedirs(LOGS, mode=0o700, exist_ok=True)
    path = os.path.join(LOGS, f"{name}-{what}.log")
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    os.close(fd)
    return path


def run_logged(cmd, log, failure):
    """Run cmd with its output in log (the Core's scripts trace secrets)."""
    with open(log, "a") as f:
        result = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, cwd=FEDERATED)
    if result.returncode != 0:
        with open(log) as f:
            tail = f.readlines()[-20:]
        sys.stderr.write("".join(tail))
        raise Refused(f"{failure} (whole log on the Core: {log}).")


def ensure_image(m, pull=False):
    """The image on this Core. pull: always from its registry (a release is
    what's published, not a same-named image built here)."""
    ref = f"{m['image']}:{m['version']}"
    if not pull and run(["docker", "image", "inspect", ref]).returncode == 0:
        return
    if m["image"].startswith("localhost/"):
        raise Refused(f"The image {ref} isn't on this Core, and localhost/ images "
                      "can't be pulled. coreapp deploy copies it here.")
    say(f"Pulling {ref}...")
    registry, owner = m["image"].split("/")[:2]
    _, token = basic_auth(registry, owner)
    # The token goes in a docker config just for this pull, so the Core
    # keeps no docker login
    with tempfile.TemporaryDirectory(prefix="coreapps-docker-") as config:
        env = dict(os.environ)
        if token:
            key = "https://index.docker.io/v1/" if registry == "docker.io" else registry
            fd = os.open(os.path.join(config, "config.json"), os.O_WRONLY | os.O_CREAT, 0o600)
            with os.fdopen(fd, "w") as f:
                json.dump({"auths": {key: {"auth": token}}}, f)
            env["DOCKER_CONFIG"] = config
        out = run(["docker", "pull", "-q", ref], env=env)
    if out.returncode != 0:
        hint = ("" if token else
                f" If it's private, give this Core a token for {registry}: coreapp login {registry}.")
        raise Refused(f"Couldn't pull {ref}: {out.stderr.strip().rstrip('.')}."
                      + (hint or " Is it published?"))


def image_digest(m):
    """The registry's digest of the pulled image:version (sha256:...), or ""."""
    out = run(["docker", "image", "inspect", "--format", "{{json .RepoDigests}}",
               f"{m['image']}:{m['version']}"])

    def short(repo):
        return repo.removeprefix("docker.io/").removeprefix("library/")
    try:
        digests = json.loads(out.stdout) if out.returncode == 0 else []
    except ValueError:
        digests = []
    for d in digests or []:
        repo, _, digest = d.partition("@")
        if short(repo) == short(m["image"]) and re.fullmatch(r"sha256:[0-9a-f]{64}", digest):
            return digest
    return ""


def set_env(name, key, value):
    """key=value in the app's .env, replacing it or added at the end."""
    path = f"{APPS}/{name}/.env"
    with open(path) as f:
        lines = [line for line in f.read().splitlines() if not line.startswith(key + "=")]
    write(path, "\n".join(lines + [f"{key}={value}"]) + "\n", 0o600)


def image_user(ref):
    """The uid:gid the image runs as, or None for root (or unknown)."""
    user = run(["docker", "image", "inspect", "-f", "{{.Config.User}}", ref]).stdout.strip()
    if user in ("", "0", "root", "0:0", "root:root"):
        return None
    if re.fullmatch(r"[0-9]+(:[0-9]+)?", user):
        uid, _, gid = user.partition(":")
        return int(uid), int(gid or uid)
    # A user name: ask the image (needs `id` in it)
    out = run(["docker", "run", "--rm", "--network", "none", "--entrypoint", "sh", ref,
               "-c", "id -u; id -g"])
    ids = out.stdout.split()
    if out.returncode == 0 and len(ids) == 2 and all(i.isdigit() for i in ids):
        return int(ids[0]), int(ids[1])
    say(f"Note: couldn't tell which user {ref} runs as ({user}); /data stays root's.")
    return None


def prepare_data(m):
    """/data, owned by the user the app runs as, so it can write there."""
    data = f"{APPS}/{m['name']}/data"
    os.makedirs(data, exist_ok=True)
    ids = image_user(f"{m['image']}:{m['version']}")
    if ids and (os.stat(data).st_uid, os.stat(data).st_gid) != ids:
        os.chown(data, *ids)


def compose_up(m, log, recreate=False):
    name = m["name"]
    prepare_data(m)
    # A release runs the image it was installed with (image:version@digest),
    # even if the tag is pushed again; a folder's image by its tag
    set_env(name, "IMAGE_DIGEST", "@" + m["digest"] if m.get("digest") else "")
    run_logged(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml",
                "-p", name, "up", "-d", "--remove-orphans",
                *(["--force-recreate"] if recreate else [])], log,
               f"Starting {name} failed")


# Run on update: the same values the generated install provides, then the
# compose file again (it may have changed), settings the new version adds,
# the setup of needs that are new, and each need's update step (keeping
# what it set up current). Arguments: name, version, new needs.
# (service sets NAME to the app's title, so the name is also in NAME_ID.)
UPDATE_SCRIPT = r'''
cd /federated
. /etc/federated
. lib/functions.sh
. lib/helpers.sh
set -e
. services/$1/service
TRAEFIK_IP="$(sed -n 's/^INTERNAL_IP=//p' services/traefik/service)"
templatize services/$1/docker-compose.yml.in > apps/$1/docker-compose.yml
fresh="$(mktemp)"
templatize services/$1/env.in > "$fresh"
while IFS= read -r line; do
  case "$line" in [A-Za-z_]*=*) ;; *) continue ;; esac
  grep -q "^${line%%=*}=" apps/$1/.env || echo "$line" >> apps/$1/.env
done < "$fresh"
rm -f "$fresh"
sed -i "s/^IMAGE_VERSION=.*/IMAGE_VERSION=$2/" apps/$1/.env
chmod 600 apps/$1/.env
shift 2
for need in "$@"; do . services/$NAME_ID/needs/$need/setup; done
for step in services/$NAME_ID/needs/*/update; do
  if [ -e "$step" ]; then . "$step"; fi
done
'''


def install(arg, addon_ok, recreate=False, downgrade=False, drop_database=False):
    with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
        folder, origin = resolve(arg, staging)
        m = read_manifest(folder)
        check_release(m, origin)
        p = plan(m, origin, downgrade, drop_database)
        return install_app(m, p, folder, origin, addon_ok, recreate)


def install_app(m, p, folder, origin, addon_ok, recreate):
    name = m["name"]
    if p["addon"] == "yes" and not addon_ok:
        say(f"This Core's tier is '{p['tier']}': installing records '{name}' as an "
            "add-on app (ADDON_APPS in /etc/federated), which Federated may bill for. "
            "Run again with --addon-ok to install anyway.")
        return 3
    if origin:
        say(f"{m['title']} {m['version']} from {origin['source']} ({origin['tag']}, "
            f"commit {origin['commit'][:12]})")
    ensure_image(m, pull=bool(origin))
    if origin:
        pin_release(m, p, origin)
    state, note = icon_check(folder)
    if state != "ok":
        say(f"Note: {note}")

    if p["new_extensions"]:
        say(f"Enabling PostgreSQL extension(s) {', '.join(p['new_extensions'])} in "
            f"{name}'s database (as the Core's superuser).")
    if p["state"] == "new":
        make_service_folder(m, p, folder, origin)
        say(f"Installing {name} at {p['address']} (the Core's installapp)...")
        log = log_path(name, "install")
        run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed")
        # installapp's start step only knows Federated's own apps
        compose_up(m, log)
        wait_until_answering(m, p)
        wait_for_route(m, p)
    else:
        before = service_value(f"{APPS}/{name}/.env", "IMAGE_VERSION")
        if before == m["version"]:
            say(f"Updating {name} ({m['version']} again{', in a new container' if recreate else ''})...")
        else:
            say(f"Updating {name} to {m['version']}...")
        log = log_path(name, "update")
        # On the apps' filesystem: /tmp may be in memory, and /data's copy
        # is a reflink, which only works within a filesystem
        for stale in glob.glob(f"{APPS}/.coreapps-rollback-{name}-*"):
            shutil.rmtree(stale, ignore_errors=True)
        with tempfile.TemporaryDirectory(prefix=f".coreapps-rollback-{name}-", dir=APPS) as backup:
            keep_for_rollback(m, p, backup, log)
            try:
                make_service_folder(m, p, folder, origin)
                # Settings of needs it drops go, so a need that gives the
                # same names (postgres, mysql: DB_*) gets its own values
                drop_env(name, p["dropped_needs"])
                env = dict(os.environ, NAME_ID=name)
                with open(log, "a") as f:
                    result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name,
                                             m["version"], *p["new_needs"]],
                                            stdout=f, stderr=subprocess.STDOUT, env=env)
                if result.returncode != 0:
                    raise Refused(f"Updating failed (whole log on the Core: {log}).")
                compose_up(m, log, recreate)
                wait_until_answering(m, p)
                wait_for_route(m, p)
            except (Exception, KeyboardInterrupt) as e:
                say(f"{e}" if isinstance(e, Refused) else f"Updating failed: {e!r}")
                raise Refused(roll_back(m, p, backup, log)) from e
            # The new version works: undo what the dropped needs set up,
            # with their teardown from before the update
            if p["dropped_needs"]:
                drop_needs(name, p["dropped_needs"], backup, log)

    check_needs(m)
    if p["state"] == "update":
        remove_old_images(m)
        # Its title, description, icon or link may have changed
        refresh_superpanel(log)
    say(f"{'Installed' if p['state'] == 'new' else 'Updated'}: {p['url']}")
    return 0


def pin_release(m, p, origin):
    """Record the pulled release's digest (m and the marker), or refuse if
    the release installed here has changed in its registry since."""
    name, ref = m["name"], f"{m['image']}:{m['version']}"
    digest = image_digest(m)
    if not digest:
        raise Refused(f"Can't read the registry's digest of {ref}.")
    before = marker_value(name, "digest") if p["state"] == "update" else ""
    if before and before != digest and marker_value(name, "tag") == origin["tag"]:
        # Put the tag back on the installed image, and drop the changed one
        run(["docker", "tag", f"{m['image']}@{before}", ref])
        run(["docker", "image", "rm", f"{m['image']}@{digest}"])
        raise Refused(f"{ref} in its registry isn't the image installed here (installed "
                      f"{before[:19]}..., now {digest[:19]}...): the release was changed after "
                      f"it was published. {name} keeps running the installed one. A new "
                      "version should have a new tag.")
    m["digest"] = origin["digest"] = digest
    say(f"Image: {ref}@{digest}")


# Kept during an update, to put back if it fails
ROLLBACK_FILES = [".env", "docker-compose.yml"]


# Its database, dumped before an update and put back if the update fails.
# Each runs in the database's container (the same version as the server);
# root's MariaDB password is read there, so it's not in a log.
DUMP = {
    # zstd at level 1: on the dev Core, a 1.3 GB database took 6 s and
    # 158 MB, against 27 s and 223 MB with pg_dump's default (gzip)
    "postgres": ("db.dump", ["docker", "exec", "postgresql",
                             "pg_dump", "-U", "postgres", "-Fc", "-Z", "zstd:1", "{db}"]),
    "mysql": ("db.sql", ["docker", "exec", "pdnsmysql", "sh", "-c",
                         'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb-dump -uroot '
                         "--single-transaction --routines --triggers --events --databases {db}"]),
}
RESTORE = {
    "postgres": [
        ["docker", "exec", "postgresql", "psql", "-U", "postgres", "-qc",
         "DROP DATABASE IF EXISTS {db} WITH (FORCE)"],
        ["docker", "exec", "postgresql", "psql", "-U", "postgres", "-qc",
         "CREATE DATABASE {db} OWNER {db}"],
        ["docker", "exec", "-i", "postgresql", "pg_restore", "-U", "postgres", "-d", "{db}"],
    ],
    "mysql": [
        ["docker", "exec", "pdnsmysql", "sh", "-c",
         'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb -uroot -e "DROP DATABASE IF EXISTS {db}"'],
        ["docker", "exec", "-i", "pdnsmysql", "sh", "-c",
         'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb -uroot'],
    ],
}


# The database's size, to check there's room for its copy first
DB_SIZE = {
    "postgres": ["docker", "exec", "postgresql", "psql", "-U", "postgres", "-Atc",
                 "SELECT pg_database_size('{db}')"],
    "mysql": ["docker", "exec", "pdnsmysql", "sh", "-c",
              'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb -uroot -N -e "SELECT '
              "COALESCE(SUM(data_length + index_length), 0) FROM information_schema.tables "
              "WHERE table_schema = '{db}'\""],
}
# Left free on the apps' disk after the database's copy, for the Core
ROLLBACK_RESERVE = 1024 ** 3
# Above this, say that keeping the copy takes a while
BIG_DATABASE = 1024 ** 3


def size_text(n):
    return f"{n / 1024 ** 3:.1f} GB" if n >= 1024 ** 3 else f"{n / 1024 ** 2:.0f} MB"


def database_size(need, db):
    out = run([c.replace("{db}", db) for c in DB_SIZE[need]])
    text = out.stdout.strip()
    return int(text) if out.returncode == 0 and text.isdigit() else None


def dump_database(cmd, dbname, path, log):
    with open(path, "wb") as out, open(log, "a") as err:
        return subprocess.run([c.replace("{db}", dbname) for c in cmd], stdout=out, stderr=err)


def keep_for_rollback(m, p, backup, log):
    """Copies of the app's service folder, settings, database and (where the
    filesystem makes it cheap) /data, in backup. Refuses the update if the
    database can't be dumped."""
    name = m["name"]
    shutil.copytree(os.path.join(SERVICES, name), os.path.join(backup, "service"),
                    symlinks=True)
    for f in ROLLBACK_FILES:
        if os.path.exists(os.path.join(APPS, name, f)):
            shutil.copy2(os.path.join(APPS, name, f), os.path.join(backup, f))
    for need in marker_needs(name):
        if need in DUMP:
            file, cmd = DUMP[need]
            # The copy is about the database's size at most (pg_dump -Fc
            # compresses; mariadb-dump's SQL is close to it)
            size = database_size(need, m["dbname"])
            free = shutil.disk_usage(backup).free
            if size is not None and size + ROLLBACK_RESERVE > free:
                raise Refused(
                    f"Updating {name} keeps a copy of its database ({size_text(size)}) until the "
                    f"update has worked, to roll back to, and the apps' disk has "
                    f"{size_text(free)} free (it keeps {size_text(ROLLBACK_RESERVE)} for the "
                    "Core). Nothing was changed. Free some space first.")
            if size is not None and size > BIG_DATABASE:
                say(f"Keeping a copy of its database ({size_text(size)}) in case the update "
                    "fails; this takes a while...")
            started = time.monotonic()
            result = dump_database(cmd, m["dbname"], os.path.join(backup, file), log)
            if result.returncode != 0 and "-Z" in cmd:
                # A PostgreSQL built without zstd: its default compression
                at = cmd.index("-Z")
                result = dump_database(cmd[:at] + cmd[at + 2:], m["dbname"],
                                       os.path.join(backup, file), log)
            if result.returncode != 0:
                raise Refused(f"Couldn't back up {name}'s database before updating, "
                              f"so nothing was changed (log on the Core: {log}).")
            if time.monotonic() - started > 30:
                say(f"Kept it ({size_text(os.path.getsize(os.path.join(backup, file)))}, "
                    f"{time.monotonic() - started:.0f} seconds).")
    # A reflink copy shares the files' blocks until one side changes (btrfs,
    # XFS); a full copy of /data could be too big, so there's none
    data = os.path.join(APPS, name, "data")
    if os.path.isdir(data):
        result = run(["cp", "-a", "--reflink=always", data, os.path.join(backup, "data")])
        if result.returncode != 0:
            shutil.rmtree(os.path.join(backup, "data"), ignore_errors=True)
            say(f"Note: this Core's filesystem can't copy /data cheaply, so if the update "
                f"fails, {name}'s /data stays as the new version leaves it.")


def restore_data(m, backup, log):
    """The database and /data as they were before the update, where
    keep_for_rollback kept them. Returns what couldn't be put back."""
    name, problems = m["name"], []
    for need, (file, _) in DUMP.items():
        dump = os.path.join(backup, file)
        if not os.path.exists(dump):
            continue
        ok = True
        with open(log, "a") as err:
            for cmd in RESTORE[need]:
                with open(dump, "rb") if "-i" in cmd else open(os.devnull, "rb") as stdin:
                    result = subprocess.run([c.replace("{db}", m["dbname"]) for c in cmd],
                                            stdin=stdin, stdout=err, stderr=err)
                ok = ok and result.returncode == 0
        if not ok:
            problems.append("putting back its database")
    data, kept = os.path.join(APPS, name, "data"), os.path.join(backup, "data")
    if os.path.isdir(kept):
        shutil.rmtree(data, ignore_errors=True)
        os.rename(kept, data)
    return problems


# Undo the setup of needs the failed update added (their teardown, from the
# new service folder). Arguments: name, needs.
ROLLBACK_SCRIPT = r'''
cd /federated
. /etc/federated
. lib/functions.sh
. lib/helpers.sh
name=$1
shift
for need in "$@"; do
  if [ -e services/$name/needs/$need/teardown ]; then . services/$name/needs/$need/teardown; fi
done
'''

# Teardown of needs an update dropped, from the service folder kept before
# it. Arguments: the kept folder, needs.
DROP_SCRIPT = r'''
cd /federated
. /etc/federated
. lib/functions.sh
. lib/helpers.sh
kept=$1
shift
for need in "$@"; do
  if [ -e "$kept/needs/$need/teardown" ]; then . "$kept/needs/$need/teardown"; fi
done
'''


def drop_env(name, needs):
    """Remove the settings these needs gave from the app's .env."""
    keys = {line.split("=", 1)[0] for n in needs
            for line in read_text(NEEDS_DIR, n, "env.in").splitlines()
            if re.match(r"[A-Z_]+=", line)}
    if not keys:
        return
    path = f"{APPS}/{name}/.env"
    with open(path) as f:
        lines = [line for line in f.read().splitlines()
                 if line.split("=", 1)[0] not in keys]
    write(path, "\n".join(lines) + "\n", 0o600)


def drop_needs(name, needs, backup, log):
    say(f"Removing what it no longer needs from the Core: {', '.join(needs)}...")
    with open(log, "a") as f:
        result = subprocess.run(["bash", "-c", DROP_SCRIPT, "drop",
                                 os.path.join(backup, "service"), *needs],
                                stdout=f, stderr=subprocess.STDOUT)
    if result.returncode != 0:
        say(f"Warning: removing {', '.join(needs)} didn't finish (log on the Core: {log}); "
            "the app runs without them.")


# After the old service folder is back: its needs' update steps, so what
# they set up matches it again (e.g. an Authelia client the update changed)
RESYNC_SCRIPT = r'''
cd /federated
. /etc/federated
. lib/functions.sh
. lib/helpers.sh
for step in services/$1/needs/*/update; do
  if [ -e "$step" ]; then . "$step"; fi
done
'''


def roll_back(m, p, backup, log):
    """Put back the version that ran before a failed update, with its
    settings, database and (if it was copied) /data, and start it. Returns
    what to tell the person."""
    name = m["name"]
    say(f"Rolling back {name}...")
    problems = []
    # The new version mustn't write while its data is put back
    run(["docker", "stop", name])
    if p["new_needs"] and os.path.isdir(os.path.join(SERVICES, name, "needs")):
        with open(log, "a") as f:
            result = subprocess.run(["bash", "-c", ROLLBACK_SCRIPT, "rollback", name,
                                     *p["new_needs"]], stdout=f, stderr=subprocess.STDOUT)
        if result.returncode != 0:
            problems.append(f"undoing needs {', '.join(p['new_needs'])}")
    # What's put back, for the message
    restored = ["its settings"]
    if any(os.path.exists(os.path.join(backup, f)) for f, _ in DUMP.values()):
        restored.append("its database")
    if os.path.isdir(os.path.join(backup, "data")):
        restored.append("/data")
    kept_data = (os.path.isdir(os.path.join(backup, "data"))
                 or not os.path.isdir(os.path.join(APPS, name, "data")))
    problems += restore_data(m, backup, log)
    final = os.path.join(SERVICES, name)
    shutil.rmtree(final, ignore_errors=True)
    shutil.rmtree(final + ".new", ignore_errors=True)
    shutil.copytree(os.path.join(backup, "service"), final, symlinks=True)
    for f in ROLLBACK_FILES:
        if os.path.exists(os.path.join(backup, f)):
            shutil.copy2(os.path.join(backup, f), os.path.join(APPS, name, f))
    with open(log, "a") as f:
        result = subprocess.run(["bash", "-c", RESYNC_SCRIPT, "resync", name],
                                stdout=f, stderr=subprocess.STDOUT)
    if result.returncode != 0:
        problems.append("putting back what its needs set up")
    try:
        old = read_manifest(final)
    except Refused:
        old = None
    with open(log, "a") as f:
        result = subprocess.run(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml",
                                 "-p", name, "up", "-d", "--remove-orphans", "--force-recreate"],
                                stdout=f, stderr=subprocess.STDOUT)
    if result.returncode != 0:
        problems.append("starting the old version")
    # The new version's image, unless it's the same tag as the old one
    if old and (old["image"], old["version"]) != (m["image"], m["version"]):
        run(["docker", "image", "rm", f"{m['image']}:{m['version']}"])
    was = f"{old['version']}" if old else "the version before"
    if problems:
        return (f"Rolling back to {was} went wrong ({'; '.join(problems)}). "
                f"Look at the log on the Core: {log}.")
    what = ", ".join(restored[:-1]) + (" and " if len(restored) > 1 else "") + restored[-1]
    note = "" if kept_data else " /data is as the new version left it."
    if old and (old["image"], old["version"]) == (m["image"], m["version"]):
        return (f"Rolled back {name} ({what} as before the update). It's the same image "
                f"tag as before ({m['version']}), so the image that failed is the one running." + note)
    return f"Rolled back: {name} {was} runs again, with {what} as before the update." + note


def short_name(image):
    """The image's name as docker lists it (docker.io/library/x is x)."""
    for prefix in ("docker.io/library/", "docker.io/"):
        if image.startswith(prefix):
            return image[len(prefix):]
    return image


def image_tags(image):
    """The tags of image on this Core."""
    out = run(["docker", "image", "ls", "--format", "{{.Repository}} {{.Tag}}"])
    return [tag for repo, _, tag in (line.partition(" ") for line in out.stdout.splitlines())
            if repo == short_name(image) and tag != "<none>"]


def remove_images(image, keep=None):
    """image's tags on this Core except keep. Without force: docker refuses
    to delete one a container uses (another app may use the same image)."""
    for tag in image_tags(image):
        if tag != keep:
            run(["docker", "image", "rm", f"{short_name(image)}:{tag}"])


def check_needs(m):
    """Say so if a need couldn't be set up (its setup only writes to the
    Core's install log)."""
    if "email" in m["needs"]:
        out = run(["bash", "-c", (
            'B=$(sed -n "s/^LDAP_SEARCH_BASE=ou=people,//p" /federated/apps/mail/.env); '
            'docker exec ldap ldapsearch -LLL -x -H ldap://localhost -D "cn=admin,$B" '
            '-w "$(cat /federated/apps/ldap/.ldap.secret)" '
            f'-b "uid=coreapp-{m["name"]},ou=people,$B" -s base description')])
        if f"description: coreapps: {m['name']}" not in out.stdout:
            say(f"Warning: {m['name']} can't send mail: LDAP has another entry with uid "
                f"coreapp-{m['name']} (or its address), which was left alone.")


def remove_old_images(m):
    """The app's images with other versions, now that this one runs."""
    remove_images(m["image"], keep=m["version"])


def wait_until_answering(m, p):
    name = m["name"]
    url = f"http://{p['address']}:{m['port']}{m['health']}"
    # As traefik sends it, so apps that check the host name answer as they
    # will to people
    headers = {"Host": f"{name}.{p['domain']}", "X-Forwarded-Proto": "https",
               "X-Forwarded-Host": f"{name}.{p['domain']}"}
    say(f"Waiting for it to answer at {url}...")
    for _ in range(30):
        state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip()
        if state not in ("running", "created", "restarting"):
            break
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=headers),
                                        timeout=2) as r:
                if 200 <= r.status < 400:
                    return
        except urllib.error.HTTPError as e:
            if e.code < 500:
                return
        except (urllib.error.URLError, OSError):
            pass
        time.sleep(2)
    logs = run(["docker", "logs", "--tail", "20", name])
    sys.stderr.write(logs.stdout + logs.stderr)
    raise Refused(f"{name} doesn't answer at {url} (state: {state or 'missing'}; "
                  "its log is above).")


def wait_for_route(m, p):
    """Until traefik routes https://<name>.<domain> to the new container
    (it answers 404 for a few seconds after a container starts)."""
    host = f"{m['name']}.{p['domain']}"
    traefik = service_value(os.path.join(SERVICES, "traefik", "service"), "INTERNAL_IP")
    if not traefik:
        return

    def status(*args):
        return run(["curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "3",
                    *args]).stdout
    # What the app itself answers there (a 404 can be the app's own, so
    # wait for traefik to give the same, not for "not 404")
    direct = status("-H", f"Host: {host}", "-H", "X-Forwarded-Proto: https",
                    f"http://{p['address']}:{m['port']}{m['health']}")
    for _ in range(30):
        code = status("--resolve", f"{host}:443:{traefik}", f"https://{host}{m['health']}")
        if code == direct or code not in ("", "000", "404", "502", "503"):
            return
        time.sleep(1)
    say(f"Note: traefik doesn't route https://{host}/ to it yet; it may take a moment.")


def update(name, addon_ok):
    """An app installed from a repository, to its newest release."""
    if not re.fullmatch(FIELDS["name"], name) or not is_ours(name):
        raise Refused(f"No app called '{name}' installed by coreapps on this Core.")
    source = marker_value(name, "source")
    if not source:
        raise Refused(f"'{name}' was installed from a folder, not a repository; "
                      "update it the same way (coreapp deploy).")
    with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
        folder, origin = resolve(source, staging)
        if origin["tag"] == marker_value(name, "tag"):
            say(f"{name} is at the newest release, {origin['tag']}.")
            return 0
        m = read_manifest(folder)
        check_release(m, origin)
        if m["name"] != name:
            raise Refused(f"At {origin['tag']}, {source} is the app '{m['name']}', not '{name}'.")
        return install_app(m, plan(m, origin), folder, origin, addon_ok, False)


def remove(name):
    if not re.fullmatch(FIELDS["name"], name):
        raise Refused(f"'{name}' isn't an app name.")
    folder = os.path.join(SERVICES, name)
    if not os.path.isdir(folder):
        raise Refused(f"No app called '{name}' on this Core.")
    if not is_ours(name):
        raise Refused(f"'{name}' wasn't installed by coreapps; it's not removed here.")
    image = service_value(os.path.join(folder, "service"), "CONTAINER")
    log = log_path(name, "remove")
    if os.path.isdir(os.path.join(APPS, name)):
        say(f"Uninstalling {name} (the Core's uninstallapp)...")
        run_logged([FEDERATED + "/bin/uninstallapp", name], log, "uninstallapp failed")
    shutil.rmtree(folder)
    if image:
        remove_images(image)
    # uninstallapp made superpanel's catalog while the folder was still
    # there, so it would still offer the app: make it again
    refresh_superpanel(log)
    say(f"Removed {name}.")
    return 0


def refresh_superpanel(log):
    """Superpanel's lists of installed apps (its dashboard) and of apps it
    offers, as installapp and uninstallapp make them."""
    if os.path.exists(APPS + "/superpanel/.env"):
        for script in ("superpanel-generate-applist-dashboard", "superpanel-generate-catalog"):
            run_logged([f"{FEDERATED}/bin/{script}"], log, f"{script} failed")
        run(["docker", "exec", "superpanel", "pkill", "-HUP", "superpanel"])


def list_apps():
    rows = []
    for name in sorted(os.listdir(SERVICES)):
        if not is_ours(name):
            continue
        service = os.path.join(SERVICES, name, "service")
        state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip()
        source = marker_value(name, "source")
        rows.append((name, service_value(service, "VERSION"),
                     service_value(service, "INTERNAL_IP"), state or "not running",
                     f"{source}@{marker_value(name, 'tag')}" if source else "(from a folder)"))
    if not rows:
        say("No apps installed by coreapps.")
    for row in rows:
        say("%-24s %-12s %-14s %-12s %s" % row)
    return 0


# --- What this Core offers apps (coreapp core) ---------------------------------------

def image_tag(container):
    """The version in a container's image tag (e.g. 4.39.22), or "?"."""
    image = run(["docker", "inspect", "-f", "{{.Config.Image}}", container]).stdout.strip()
    tag = image.rsplit(":", 1)[1] if ":" in image.rsplit("/", 1)[-1] else ""
    return tag.lstrip("v") or "?"


def core_info():
    """The Core's services, versions and machine, as apps see them."""
    domain, _ = federated_settings()
    rows = [("Domain", domain)]
    rows.append(("PostgreSQL", (db_version("postgres") or "?") + '  (needs = ["postgres"])'))
    ext = run(["docker", "exec", "postgresql", "psql", "-U", "postgres", "-Atc",
               "SELECT v.trusted, string_agg(e.name || ' ' || e.default_version, ', ' ORDER BY e.name) "
               "FROM pg_available_extensions e JOIN pg_available_extension_versions v "
               "ON v.name = e.name AND v.version = e.default_version "
               "WHERE e.name <> 'plpgsql' GROUP BY v.trusted ORDER BY v.trusted DESC"]).stdout
    for line in ext.splitlines():
        trusted, _, names = line.partition("|")
        rows.append(("  extensions the app can enable" if trusted == "t" else
                     "  extensions only the Core can enable", names))
    rows.append(("MariaDB", (db_version("mysql") or "?") + '  (needs = ["mysql"])'))
    rows.append(("Authelia", image_tag("authelia") + '  (needs = ["sso"], OpenID Connect)'))
    rows.append(("Mail server", "docker-mailserver " + image_tag("mail")
                 + '  (needs = ["email"], sending with SMTP and STARTTLS)'))
    rows.append(("Traefik", image_tag("traefik") + "  (HTTPS and certificates in front of apps)"))
    docker = run(["docker", "version", "--format", "{{.Server.Version}}"]).stdout.strip()
    compose = run(["docker", "compose", "version", "--short"]).stdout.strip()
    rows.append(("Docker", f"{docker or '?'}, Compose {compose or '?'}  (one container per app)"))
    arch = os.uname().machine
    mem = 0
    with open("/proc/meminfo") as f:
        for line in f:
            if line.startswith("MemTotal:"):
                mem = int(line.split()[1]) / 1024 / 1024
    disk = shutil.disk_usage(APPS)
    fstype = run(["findmnt", "-no", "FSTYPE", "--target", APPS]).stdout.strip()
    rows.append(("Machine", f"{arch} ({'amd64' if arch == 'x86_64' else arch} images), "
                 f"{os.cpu_count()} CPUs, {mem:.1f} GB memory"))
    rows.append(("Apps' disk", f"{disk.free / 1e9:.0f} GB free of {disk.total / 1e9:.0f} GB, "
                 f"{fstype or '?'} (/data)"))
    rows.append(("Names apps can't use", ", ".join(sorted(federated_names() | RESERVED))
                 + "  (Federated's apps, installed or not, and the Core's host names)"))
    rows.append(("Not offered", "Redis or other services, a second container, extra host names, "
                 "public ports other than HTTPS, the Core's AI model"))
    for label, value in rows:
        print(f"{label + ':':<38} {value}")
    return 0


# --- The app's mail (coreapp mail) ---------------------------------------------------

def app_mail(name, since="24h"):
    """What the Core's mail server did with the mail the app sent: accepted
    from its account, then delivered, deferred or bounced, per recipient."""
    if not re.fullmatch(FIELDS["name"], name) or not is_ours(name):
        raise Refused(f"No app called '{name}' installed by coreapps on this Core.")
    out = run(["docker", "logs", "--since", since, "mail"])
    lines = (out.stdout + out.stderr).splitlines()
    account = re.compile(r" ([0-9A-F]{6,}): client=\S+, sasl_method=\S+, sasl_username=coreapp-"
                         + re.escape(name) + r"@")
    ids = {}
    for line in lines:
        found = account.search(line)
        if found:
            ids[found.group(1)] = line[:19].replace("T", " ")
    if not ids:
        say(f"The Core's mail server has no mail from {name} in the last {since} "
            f"(from its account, coreapp-{name}).")
        return 0
    for qid, when in list(ids.items())[-20:]:
        sender, results = "", []
        for line in lines:
            if f" {qid}: " not in line:
                continue
            found = re.search(r"from=<([^>]*)>", line)
            if found and not sender:
                sender = found.group(1)
            found = re.search(r"to=<([^>]*)>.*status=(\w+)(?: \((.*)\))?", line)
            if found:
                to, status, why = found.groups()
                results.append(f"  to {to}: {status}"
                               + (f" ({why[:160]})" if why and status != "sent" else ""))
        say(f"{when}  from {sender or '?'}, accepted")
        for r in dict.fromkeys(results):
            say(r)
        if not results:
            say("  (no delivery yet)")
    return 0


# --- The test account (coreapp signin) ---------------------------------------------

# A person in the Core's LDAP that coreapp signin signs in with, on a
# developer's own Core. Its uid has a dot, which no app name has, so it is
# never an app's mail account (coreapp-<name>).
TEST_UID = "coreapp.test"
TEST_DESCRIPTION = "coreapps: test account for coreapp signin"
# Its mailbox, so mail apps send it is delivered (coreapp inbox reads it).
# The Core's mail server delivers to entries with mailEnabled TRUE, and its
# Dovecot needs a homeDirectory. People get that from posixAccount, which
# also needs a uidNumber; extensibleObject gives it without one, so the
# test account never takes a number Superpanel would give a person.
TEST_MAILBOX = {"objectClass": ["PostfixBookMailAccount", "extensibleObject"],
                "mailEnabled": ["TRUE"], "homeDirectory": [f"/home/{TEST_UID}"]}
INBOX_SHOWN = 10
INBOX_TEXT = 4000


def ldap_base():
    return service_value(APPS + "/mail/.env", "LDAP_SEARCH_BASE").removeprefix("ou=people,")


def ldap(args, stdin=None):
    """Run an LDAP tool in the Core's ldap container, as its admin."""
    with open(APPS + "/ldap/.ldap.secret") as f:
        admin_pw = f.read().strip()
    return run(["docker", "exec", "-i", "ldap", args[0], "-x", "-H", "ldap://localhost",
                "-D", f"cn=admin,{ldap_base()}", "-w", admin_pw] + args[1:], input=stdin or "")


def test_account(remove=False):
    """Make or refresh the test person with the password on stdin (or
    remove it). Only an entry this made is changed."""
    domain, _ = federated_settings()
    mail = f"{TEST_UID}@{domain}"
    base = ldap_base()
    if not base or not os.path.exists(APPS + "/ldap/.ldap.secret"):
        raise Refused("Can't find the Core's LDAP settings.")
    found = ldap(["ldapsearch", "-LLL", "-o", "ldif-wrap=no", "-b", base,
                  f"(|(uid={TEST_UID})(mail={mail}))", "description"])
    maildir = test_maildir(domain)
    if found.returncode != 0:
        raise Refused(f"Can't search the Core's LDAP: {found.stderr.strip()}")
    dn = f"uid={TEST_UID},ou=people,{base}"
    ours = f"dn: {dn}\ndescription: {TEST_DESCRIPTION}"
    entries = found.stdout.strip()
    if entries and entries != ours:
        raise Refused(f"LDAP already has an entry with uid {TEST_UID} or {mail} that "
                      "coreapps didn't make; left it alone.")
    if remove:
        if entries:
            out = ldap(["ldapdelete", dn])
            if out.returncode != 0:
                raise Refused(f"Can't remove {dn}: {out.stderr.strip()}")
            shutil.rmtree(maildir, ignore_errors=True)
            say(f"Removed the test account {mail}, with its mailbox.")
        else:
            say("There's no test account.")
        return 0
    password = sys.stdin.read()
    if len(password) < 16:
        raise Refused("Give the test account's password (16 characters or more) on stdin.")
    if not entries:
        out = ldap(["ldapadd"], f"""dn: {dn}
objectClass: inetOrgPerson
uid: {TEST_UID}
cn: Coreapp Test
givenName: Coreapp
sn: Test
mail: {mail}
description: {TEST_DESCRIPTION}
userPassword: {{CRYPT}}!
""" + "".join(f"{key}: {v}\n" for key, values in TEST_MAILBOX.items() for v in values))
        if out.returncode != 0:
            raise Refused(f"Can't add the test account: {out.stderr.strip()}")
    else:
        add_test_mailbox(dn)
    # The server hashes it
    out = ldap(["ldappasswd", "-T", "/dev/stdin", dn], password)
    if out.returncode != 0:
        raise Refused(f"Can't set the test account's password: {out.stderr.strip()}")
    print(mail)
    return 0


def add_test_mailbox(dn):
    """Give a test account made before it had one its mailbox."""
    found = ldap(["ldapsearch", "-LLL", "-o", "ldif-wrap=no", "-b", dn, "-s", "base",
                  "(objectClass=*)", *TEST_MAILBOX]).stdout.lower()
    # Only the values it lacks: adding one that's there is an error
    changes = []
    for key, values in TEST_MAILBOX.items():
        missing = [v for v in values if f"{key.lower()}: {v.lower()}" not in found]
        if missing:
            changes.append(f"add: {key}\n" + "".join(f"{key}: {v}\n" for v in missing))
    if not changes:
        return
    out = ldap(["ldapmodify"], f"dn: {dn}\nchangetype: modify\n" + "-\n".join(changes))
    if out.returncode != 0:
        raise Refused(f"Can't give the test account its mailbox: {out.stderr.strip()}")


def test_maildir(domain):
    """Where the Core's mail server keeps the test account's mail."""
    return os.path.join(APPS, "mail", "data", "var", "mail", domain.lower(), TEST_UID)


class TextOfHTML(html.parser.HTMLParser):
    """An HTML mail's text, with each link's address after it."""

    def __init__(self):
        super().__init__()
        self.parts, self.href, self.skip = [], None, 0

    def handle_starttag(self, tag, attrs):
        if tag in ("style", "script", "head"):
            self.skip += 1
        elif tag == "a":
            self.href = dict(attrs).get("href")
        elif tag in ("br", "p", "div", "tr", "li", "h1", "h2", "h3", "table"):
            self.parts.append("\n")

    def handle_endtag(self, tag):
        if tag in ("style", "script", "head"):
            self.skip = max(0, self.skip - 1)
        elif tag == "a" and self.href:
            self.parts.append(f" <{self.href}>")
            self.href = None

    def handle_data(self, data):
        if not self.skip:
            self.parts.append(data)

    def text(self):
        lines = (" ".join(line.split()) for line in "".join(self.parts).splitlines())
        return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()


def mail_text(message):
    """A message's text: its plain-text part, or its HTML part as text."""
    part = message.get_body(preferencelist=("plain", "html"))
    if part is None:
        return "(no text in it)"
    try:
        content = part.get_content()
    except (LookupError, UnicodeError):
        content = part.get_payload(decode=True).decode("utf-8", "replace")
    if part.get_content_subtype() == "html":
        parser = TextOfHTML()
        parser.feed(content)
        content = parser.text()
    content = content.strip()
    if len(content) > INBOX_TEXT:
        content = content[:INBOX_TEXT] + f"\n... ({len(content) - INBOX_TEXT} more characters)"
    return content


def test_inbox(clear=False):
    """The newest mail in the test account's mailbox, or empty it."""
    domain, _ = federated_settings()
    address = f"{TEST_UID}@{domain}"
    folder = test_maildir(domain)
    paths = [os.path.join(folder, sub, f) for sub in ("new", "cur")
             if os.path.isdir(os.path.join(folder, sub))
             for f in os.listdir(os.path.join(folder, sub)) if not f.startswith(".")]
    if clear:
        for path in paths:
            os.remove(path)
        say(f"Emptied {address}'s inbox ({len(paths)} message(s)).")
        return 0
    if not paths:
        say(f"{address}'s inbox is empty. (coreapp mail shows whether the app's mail "
            "was delivered.)")
        return 0
    paths.sort(key=os.path.getmtime)
    shown = paths[-INBOX_SHOWN:]
    say(f"{address}'s inbox: {len(paths)} message(s)"
        + (f", the newest {len(shown)}" if len(shown) < len(paths) else "") + ", oldest first.")
    for path in shown:
        with open(path, "rb") as f:
            message = email.parser.BytesParser(policy=email.policy.default).parse(f)
        when = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(os.path.getmtime(path)))
        say(f"\n=== {when} UTC")
        for header in ("From", "To", "Subject"):
            say(f"{header}: {message.get(header, '')}")
        say("")
        say(mail_text(message))
    return 0


# --- Command line -----------------------------------------------------------------

def main(args):
    if not args or args[0] in ("-h", "--help", "help"):
        print(__doc__.split("\n\n", 2)[2].strip())
        return 0
    cmd, rest = args[0], args[1:]
    if cmd == "manifest" and len(rest) == 1:
        m = read_manifest(rest[0])
        for key in ("name", "title", "description", "version", "image", "port",
                    "health", "docs", "dbname"):
            print(f"{key}={m[key]}")
        print(f"needs={' '.join(m['needs'])}")
        if "sso" in m["needs"]:
            for key, value in m["sso"].items():
                print(f"sso_{key}={str(value).lower() if isinstance(value, bool) else value}")
        state, note = icon_check(rest[0])
        print(f"icon={state}")
        print(f"icon_note={note}")
        return 0
    if os.geteuid() != 0:
        raise Refused("Run coreapps as root on the Core.")
    downgrade = "--downgrade" in rest
    drop_database = "--drop-database" in rest
    rest = [a for a in rest if a not in ("--downgrade", "--drop-database")]
    if cmd == "plan" and len(rest) == 1:
        with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
            folder, origin = resolve(rest[0], staging)
            m = read_manifest(folder)
            check_release(m, origin)
            p = plan(m, origin, downgrade, drop_database)
        for key in ("name", "title", "description", "version", "image"):
            print(f"{key}={m[key]}")
        print(f"needs={' '.join(m['needs'])}")
        for key, value in p.items():
            print(f"{key}={' '.join(value) if isinstance(value, list) else value}")
        return 0
    if cmd == "install" and rest:
        addon_ok = "--addon-ok" in rest
        recreate = "--recreate" in rest
        folders = [a for a in rest if a not in ("--addon-ok", "--recreate")]
        if len(folders) == 1:
            return install(folders[0], addon_ok, recreate, downgrade, drop_database)
    if cmd == "update" and rest:
        names = [a for a in rest if a != "--addon-ok"]
        if len(names) == 1:
            return update(names[0], "--addon-ok" in rest)
    if cmd == "remove" and len(rest) == 1:
        return remove(rest[0])
    if cmd == "login" and len(rest) == 2:
        return login(rest[0], rest[1])
    if cmd == "logout" and len(rest) == 1:
        return logout(rest[0])
    if cmd == "logins" and not rest:
        return list_logins()
    if cmd == "list" and not rest:
        return list_apps()
    if cmd == "mail" and len(rest) == 1:
        return app_mail(rest[0])
    if cmd == "core" and not rest:
        return core_info()
    if cmd == "test-account" and rest in ([], ["--remove"]):
        return test_account(remove=bool(rest))
    if cmd == "test-inbox" and rest in ([], ["--clear"]):
        return test_inbox(clear=bool(rest))
    sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n")
    return 2


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except Refused as e:
        sys.stderr.write(f"{e}\n")
        sys.exit(1)
