#!/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 <source>               what install would do on this Core
coreapps install [--addon-ok] [--recreate] <source>
                                     install the app, or update it
                                     (--recreate: a new container even if
                                     nothing changed)
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> <user>         keep a token (read from stdin) for
                                     installing private apps from host
coreapps logout <host>               forget host's token
coreapps logins                      the hosts this Core has tokens for

<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 json
import os
import re
import shutil
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,
}
REQUIRED = ["name", "title", "version", "image", "port"]

# 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, by host (root only)
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}"
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_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": []}
    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).")
        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 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 {host: c for host, c in data.items()
            if 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. Manage with\n"
            "# 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):
    """'user:token' in base64 for host, or None."""
    c = read_credentials().get(host)
    if not c:
        return None
    return base64.b64encode(f"{c['user']}:{c['token']}".encode()).decode()


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(host, user):
    host = host.lower()
    if not re.fullmatch(HOST, host):
        raise Refused(f"'{host}' isn't a host name (like gitea.example.com).")
    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[host] = {"user": user, "token": token}
    write_credentials(creds)
    say(f"Saved a token for {user}@{host}"
        + (" (its registry accepts it)." if ok else " (couldn't check it with its registry)."))
    return 0


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


def list_logins():
    creds = read_credentials()
    if not creds:
        say("No tokens: this Core installs public apps only.")
    for host in sorted(creds):
        say(f"{host}  (user {creds[host]['user']})")
    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 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)
    token = basic_auth(host)
    auth = (f"https://{host}", token) if token else None
    no_access = ("" if token else
                 f" If it's private, give this Core a token for {host}: coreapp login {host}.")
    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 plan(m, origin=None):
    """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 os.path.exists(os.path.join(SERVICES, name)) and not is_ours(name):
        raise Refused(f"This Core already has an app called '{name}' "
                      f"({service_value(os.path.join(SERVICES, name, 'service'), 'CONTAINER') or 'Federated'}). "
                      "Pick another name.")
    if os.path.exists(os.path.join(FEDERATED, "lib", name + ".sh")):
        raise Refused(f"'{name}' is the name of one of Federated's apps. Pick another name.")
    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"]]
        if dropped:
            raise Refused(f"The new coreapp.toml drops needs {', '.join(dropped)}; "
                          "removing them would delete what the app keeps there. "
                          "Remove the app and install it again to do that.")
        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.")
    else:
        p["new_needs"] = list(m["needs"])
    for key in ("source", "tag", "commit"):
        if origin:
            p[key] = origin[key]
    return p


# --- 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)


def icon_from(folder):
    """The app's icon.png if it's a reasonable PNG, else the default."""
    path = os.path.join(folder, "icon.png")
    try:
        if not os.path.islink(path) and os.path.getsize(path) <= 1024 * 1024:
            with open(path, "rb") as f:
                if f.read(8) == b"\x89PNG\r\n\x1a\n":
                    return path
    except OSError:
        pass
    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"],
        "DOCS": m["docs"], "IMAGE": m["image"], "VERSION": m["version"],
        "IP": p["address"], "PORT": str(m["port"]), "DBNAME": m["dbname"],
        "DEPENDS": " ".join(read_text(NEEDS_DIR, n, "depends").strip() for n in m["needs"]),
    }
    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")
                    if origin))
    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 = m["image"].split("/", 1)[0]
    token = basic_auth(registry)
    # 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_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)
    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):
    with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
        folder, origin = resolve(arg, staging)
        m = read_manifest(folder)
        check_release(m, origin)
        p = plan(m, origin)
        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 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)
    else:
        say(f"Updating {name} to {m['version']}...")
        log = log_path(name, "update")
        with tempfile.TemporaryDirectory(prefix="coreapps-rollback-") as backup:
            keep_for_rollback(name, backup)
            try:
                make_service_folder(m, p, folder, origin)
                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)
            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

    check_needs(m)
    if p["state"] == "update":
        remove_old_images(m)
    say(f"{'Installed' if p['state'] == 'new' else 'Updated'}: {p['url']}")
    return 0


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


def keep_for_rollback(name, backup):
    """Copies of the app's service folder and settings, in backup."""
    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))


# 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
'''


def roll_back(m, p, backup, log):
    """Put back the version that ran before a failed update, and start it.
    The app's data (/data, its database) stays as the new version left it.
    Returns what to tell the person."""
    name = m["name"]
    say(f"Rolling back {name}...")
    problems = []
    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'])}")
    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))
    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}.")
    if old and (old["image"], old["version"]) == (m["image"], m["version"]):
        return (f"Rolled back {name}'s settings. It's the same image tag as before "
                f"({m['version']}), so the image that failed is the one running.")
    return (f"Rolled back: {name} {was} runs again, with its settings. Its data "
            "(/data, its database) is as the new version left it.")


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']}"
    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(url, 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 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, as installapp
    # does
    if os.path.exists(APPS + "/superpanel/.env"):
        run_logged([FEDERATED + "/bin/superpanel-generate-catalog"], log,
                   "Updating superpanel's app catalog failed")
        run(["docker", "exec", "superpanel", "pkill", "-HUP", "superpanel"])
    say(f"Removed {name}.")
    return 0


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


# --- 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'])}")
        return 0
    if os.geteuid() != 0:
        raise Refused("Run coreapps as root on the Core.")
    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)
        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)
    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()
    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)
