#!/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 <dir>                  what install would do on this Core
coreapps install [--addon-ok] <dir>  install the app, or update it
coreapps remove <name>               uninstall an app installed by coreapps
coreapps list                        the apps installed by coreapps

`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 json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import tomllib
import urllib.error
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, away from Federated's 192.168.0.x (all in the core
# network's 192.168.0.0/16)
PREFIX = "192.168.200."
FIRST, LAST = 10, 250
# 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", "sso"]

# 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"]


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")
    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]
        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."""
    if is_ours(name):
        ip = service_value(os.path.join(SERVICES, name, "service"), "INTERNAL_IP")
        if ip:
            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}.")


def plan(m):
    """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]
    else:
        p["new_needs"] = list(m["needs"])
    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 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):
    """/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"):
            write(os.path.join(new, "needs", need, step),
                  fill(read_text(NEEDS_DIR, need, step), 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")
    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):
    ref = f"{m['image']}:{m['version']}"
    if 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}...")
    out = run(["docker", "pull", "-q", ref])
    if out.returncode != 0:
        raise Refused(f"Couldn't pull {ref}: {out.stderr.strip()}")


def compose_up(name, log):
    run_logged(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml",
                "-p", name, "up", "-d", "--remove-orphans"], 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,
# and the setup of needs that are new. Arguments: name, version, 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
'''


def install(folder, addon_ok):
    m = read_manifest(folder)
    p = plan(m)
    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
    ensure_image(m)
    make_service_folder(m, p, folder)

    if p["state"] == "new":
        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(name, log)
    else:
        say(f"Updating {name} to {m['version']}...")
        log = log_path(name, "update")
        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(name, log)

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


def remove_old_images(m):
    """The app's images with other versions, now that this one runs."""
    out = run(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}", m["image"]])
    for ref in out.stdout.split():
        if ref != f"{m['image']}:{m['version']}":
            run(["docker", "image", "rm", ref])


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 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:
        ids = run(["docker", "image", "ls", "-q", image]).stdout.split()
        for image_id in sorted(set(ids)):
            run(["docker", "image", "rm", "-f", image_id])
    # 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()
        rows.append((name, service_value(service, "VERSION"),
                     service_value(service, "INTERNAL_IP"), state or "not running"))
    if not rows:
        say("No apps installed by coreapps.")
    for row in rows:
        say("%-24s %-12s %-16s %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:
        p = plan(read_manifest(rest[0]))
        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
        folders = [a for a in rest if a != "--addon-ok"]
        if len(folders) == 1:
            return install(folders[0], addon_ok)
    if cmd == "remove" and len(rest) == 1:
        return remove(rest[0])
    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)
