#!/usr/bin/env bash
#
# Purpose : Make, deploy and test apps for Federated Core, against the Core
#           in coreapp-dev's VM (coreapp-vm).
#
# coreapp new [--postgres | --mysql] [--sso] [--email] <name>
#                          make a new app in ./<name> (with its own database,
#                          sign-in through the Core's Authelia, sending mail)
# coreapp deploy [--recreate]
#                          build, copy to the Core, install or update
#                          (--recreate: a new container even if nothing changed)
# coreapp check            the app answers at https://<name>.<domain>/
# coreapp status           its container, address and URL
# coreapp logs [-f]        its log
# coreapp shell [command]  a shell in its container, or run one command there
# coreapp mail             what the Core's mail server did with the mail the
#                          app sent in the last day (accepted, delivered,
#                          deferred, bounced; apps with "email")
# coreapp core             what the Core in the VM offers apps: its database,
#                          sign-in and mail servers with their versions,
#                          PostgreSQL extensions, and the machine
# coreapp signin [path]    sign in to it with the Core's test account, as a
#                          browser would, starting at path (default /login;
#                          a page whose button starts sign-in is pressed,
#                          --form <action> picks the form); --cookies <file>
#                          keeps the app's cookies
# coreapp signin --code    for sign-in started in the browser's JavaScript:
#                          get a code for the app's callback from Authelia
# coreapp signin --remove-account
#                          remove the test account from the Core
# coreapp remove           uninstall it from the Core (asks first)
# coreapp list             the apps on the Core installed this way
# coreapp install [--downgrade] <https://host/owner/repo>[@tag]
#                          install a published app from its repository, as
#                          a Core's owner would (shows what it needs first;
#                          --downgrade: allow an older release than the
#                          installed one)
# coreapp update <name>    update an app installed from a repository to its
#                          newest release
# coreapp login <host>     give the Core a token for private apps from host
#                          (asks for the user and token); logout <host>,
#                          logins: forget one, list them
# coreapp publish [--platform <list>]
#                          build the release image and push it to the
#                          registry in coreapp.toml, and tag the commit
#
# Run deploy, check, status, logs, shell, signin, remove and publish in the app's
# folder (the one with coreapp.toml). COREAPP_VM picks the VM (default coreserver).

set -euo pipefail

SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
TEMPLATES="$(dirname "$SELF_DIR")/templates"
TEMPLATE="$TEMPLATES/app"
# The installer that runs on the Core (coreapps), and where it goes there
INSTALLER="$(dirname "$SELF_DIR")/core"
SIGNIN="$(dirname "$SELF_DIR")/lib/signin.py"
REMOTE_INSTALLER=/opt/coreapps
DATA="$HOME/.local/share/coreapp-dev"
SSH_KEY="$DATA/ssh/id_ed25519"
KNOWN_HOSTS="$DATA/ssh/known_hosts"
VM="${COREAPP_VM:-coreserver}"

die() { echo "$*" >&2; exit 1; }

usage() {
  # The command list at the top of this file, continuation lines included
  sed -n '/^# coreapp new/,/^#$/{/^#$/d;s/^# //p}' "${BASH_SOURCE[0]}"
}

# --- The Core -------------------------------------------------------------

CORE_IP=""
# Look up the VM's address once, in this shell (not in a $(...) subshell,
# which would forget it)
init_core() {
  if [[ -z "$CORE_IP" ]]; then
    CORE_IP="$("$SELF_DIR/coreapp-vm" ip "$VM" 2> /dev/null)" \
      || die "The Core's VM '$VM' isn't running: coreapp-vm start $VM"
  fi
}
core_ip() { init_core; echo "$CORE_IP"; }

# Run a shell command on the Core as root (stdin is passed through)
core() {
  ssh -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
    -o StrictHostKeyChecking=accept-new -o BatchMode=yes \
    "root@$(core_ip)" "$1"
}

# The same, with a terminal (for shells and following logs)
core_tty() {
  ssh -t -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
    -o StrictHostKeyChecking=accept-new "root@$(core_ip)" "$1"
}

DOMAIN=""
core_domain() {
  if [[ -z "$DOMAIN" ]]; then
    # shellcheck disable=SC2016 # expanded on the Core
    DOMAIN="$(core '. /etc/federated; echo "$DOMAIN"')"
    [[ -n "$DOMAIN" ]] || die "The VM has no Core installed yet (no DOMAIN in /etc/federated)."
  fi
  echo "$DOMAIN"
}

# --- The app in the current folder ---------------------------------------

# From coreapp.toml, as checked by the installer
NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS="" ICON="" ICON_NOTE=""
SSO_CALLBACK="" SSO_PKCE=""
load_app() {
  load_manifest
  init_core
}

# coreapp.toml's values, checked by the installer (no Core needed)
load_manifest() {
  local values key value
  [[ -f coreapp.toml ]] \
    || die "No app here: run this in an app's folder (one with coreapp.toml), or make one with coreapp new <name>."
  values="$(python3 "$INSTALLER/coreapps" manifest .)" || exit 1
  while IFS='=' read -r key value; do
    case "$key" in
      name) NAME="$value" ;;
      title) TITLE="$value" ;;
      version) VERSION="$value" ;;
      image) IMAGE="$value" ;;
      port) PORT="$value" ;;
      health) HEALTH="$value" ;;
      needs) NEEDS="$value" ;;
      icon) ICON="$value" ;;
      icon_note) ICON_NOTE="$value" ;;
      sso_callback) SSO_CALLBACK="$value" ;;
      sso_pkce) SSO_PKCE="$value" ;;
    esac
  done <<< "$values"
}

image() { echo "$IMAGE:$VERSION"; }

# Put the installer on the Core, as this coreapp-dev has it
sync_installer() {
  tar -C "$INSTALLER" --exclude=__pycache__ --exclude=.claude -cf - . | core "
    set -e
    rm -rf $REMOTE_INSTALLER.new && mkdir -p $REMOTE_INSTALLER.new
    tar --no-same-owner -xf - -C $REMOTE_INSTALLER.new
    rm -rf $REMOTE_INSTALLER && mv $REMOTE_INSTALLER.new $REMOTE_INSTALLER"
}

# Run the installer on the Core with this app's coreapp.toml and icon.png,
# copied to a temporary folder there: coreapps <command> [options] <folder>
installer() {
  local files=(coreapp.toml)
  [[ -f icon.png ]] && files+=(icon.png)
  tar -cf - "${files[@]}" | core "
    d=\$(mktemp -d) && tar --no-same-owner -xf - -C \$d || exit 1
    $REMOTE_INSTALLER/coreapps $* \$d; status=\$?
    rm -rf \$d; exit \$status"
}

# --- new --------------------------------------------------------------------

# Lay an overlay over the app in $1: its files replace the app's, except
# *.append (added to the end of the app's file), .remove (app files it
# doesn't use) and .needs (what it needs from the Core, for coreapp.toml)
apply_overlay() {
  local app="$1" overlay="$2" f
  tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.needs \
    --exclude='*.append' -cf - . | tar -C "$app" -xf -
  for f in "$overlay"/*.append; do
    [[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)"
  done
  if [[ -f "$overlay/.remove" ]]; then
    while read -r f; do [[ -n "$f" ]] && rm -rf "${app:?}/$f"; done < "$overlay/.remove"
  fi
}

cmd_new() {
  local name="" postgres="" mysql="" sso="" email="" title dbname f needs="" what=""
  local overlays=()
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --postgres) postgres=1 ;;
      --mysql) mysql=1 ;;
      --sso) sso=1 ;;
      --email) email=1 ;;
      -*) die "Unknown option $1. Usage: coreapp new [--postgres | --mysql] [--sso] [--email] <name>" ;;
      *) name="$1" ;;
    esac
    shift
  done
  [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE"
  [[ -n "$name" ]] || die "Usage: coreapp new [--postgres | --mysql] [--sso] [--email] <name>   (lowercase letters, digits and -)"
  [[ -z "$postgres" || -z "$mysql" ]] || die "--postgres or --mysql, not both."
  [[ "$name" =~ ^[a-z]([a-z0-9-]{0,29}[a-z0-9])$ ]] \
    || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter and not ending with -. It becomes https://$name.<domain>."
  [[ ! -e "$name" ]] || die "./$name already exists."

  # In this order; with both, the combined example app goes on top
  [[ -n "$postgres" ]] && overlays+=("$TEMPLATES/postgres")
  [[ -n "$sso" ]] && overlays+=("$TEMPLATES/sso")
  [[ -n "$postgres" && -n "$sso" ]] && overlays+=("$TEMPLATES/postgres-sso")
  for f in "${overlays[@]}"; do
    [[ -d "$f" ]] || die "The template $f is missing."
  done

  # "my-app" -> "My App". The database name is the installer's (coreapps)
  title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')"
  dbname="coreapp_${name//-/_}"

  mkdir "$name"
  tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf -
  for f in "${overlays[@]}"; do
    apply_overlay "$name" "$f"
    [[ -f "$f/.needs" ]] && needs="$needs, \"$(cat "$f/.needs")\""
  done
  # No example apps for mysql and email: the settings are in README.md
  [[ -n "$mysql" ]] && needs="\"mysql\"$needs"
  [[ -n "$email" ]] && needs="$needs, \"email\""
  sed -i "s/^needs = .*/needs = [${needs#, }]/" "$name/coreapp.toml"
  # The example apps with a database or sign-in are Python, not www/
  # shellcheck disable=SC2016  # backquotes are Markdown
  [[ -d "$name/www" ]] || sed -i 's|`www/`|the `.py` files|g' "$name/README.md"
  # The example apps with a database or sign-in have a /health path
  [[ ${#overlays[@]} -gt 0 ]] && sed -i 's|^health = .*|health = "/health"|' "$name/coreapp.toml"

  while IFS= read -r -d '' f; do
    sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{DBNAME}}/$dbname/g" "$f"
  done < <(find "$name" -type f ! -name '*.png' -print0)

  [[ -n "$postgres$mysql" ]] && what=", with a database"
  [[ -n "$sso" ]] && what="$what, with sign-in through Authelia"
  [[ -n "$email" ]] && what="$what, sending mail"
  echo "Made $title in ./$name$what."
  echo "Next: cd $name && coreapp deploy"
}

# --- deploy -----------------------------------------------------------------

cmd_deploy() {
  local plan state tier answer local_id core_id addon="" recreate=""
  case "${1:-}" in
    --recreate) recreate=--recreate ;;
    "") ;;
    *) die "Usage: coreapp deploy [--recreate]" ;;
  esac
  load_app
  # (The installer tells about an icon it can't use)
  [[ "$ICON" != ok || -z "$ICON_NOTE" ]] || echo "Note: $ICON_NOTE"

  echo "Updating the installer on the Core ($REMOTE_INSTALLER)..."
  sync_installer
  # What installing would do (and whether the Core refuses it: name taken...)
  plan="$(installer plan)" || exit 1
  state="$(sed -n 's/^state=//p' <<< "$plan")"
  tier="$(sed -n 's/^tier=//p' <<< "$plan")"
  if grep -qx 'addon=yes' <<< "$plan"; then
    echo "This Core's tier is '$tier'. Installing records '$NAME' as an add-on app"
    echo "(ADDON_APPS in /etc/federated), which Federated may bill for."
    read -r -p "Install anyway? [y/N] " answer
    [[ "$answer" =~ ^[Yy] ]] || die "Not deployed."
    addon=--addon-ok
  fi

  echo "Building $(image)..."
  docker build -q -t "$(image)" . > /dev/null

  # localhost/ images exist only where they're copied; others the Core can
  # pull, but while developing, the one just built is the one to test
  local_id="$(docker image inspect -f '{{.Id}}' "$(image)")"
  core_id="$(core "docker image inspect -f '{{.Id}}' $(image) 2> /dev/null || true")"
  if [[ "$local_id" != "$core_id" ]]; then
    echo "Copying the image to the Core ($(docker image inspect -f '{{.Size}}' "$(image)" | numfmt --to=iec))..."
    docker save "$(image)" | core "docker load -q > /dev/null"
  else
    echo "The Core already has this image."
  fi

  # Install, or update (which recreates the container if the image changed,
  # even under the same version)
  installer install $addon $recreate || exit 1
  [[ "$state" == new ]] && echo "(coreapp check tests it at its public address, as people reach it.)"
  return 0
}

# --- check, status, logs, shell, remove ------------------------------------

cmd_check() {
  local domain url result code verify tries=24
  load_app
  domain="$(core_domain)"
  url="https://$NAME.$domain$HEALTH"
  echo "Checking $url (expecting HTTP 2xx and a valid certificate)..."
  # A new app's certificate can take a minute: traefik gets it from Let's
  # Encrypt through the Core's DNS
  while true; do
    result="$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{ssl_verify_result}' "$url" 2>&1 || true)"
    code="${result%% *}"
    verify="${result##* }"
    if [[ "$code" =~ ^2 && "$verify" == 0 ]]; then
      echo "OK: HTTP $code, valid certificate."
      return 0
    fi
    tries=$((tries - 1))
    if ((tries == 0)); then break; fi
    sleep 5
  done
  echo "Not OK: $result (HTTP code, then 0 if the certificate is valid)." >&2
  # Is it the app, or the way in?
  result="$(curl -sSk -o /dev/null --max-time 15 -w '%{http_code}' \
    --resolve "$NAME.$domain:443:$(core_ip)" "$url" 2>&1 || true)"
  echo "Straight to the VM, skipping DNS and the relay: HTTP $result." >&2
  exit 1
}

cmd_status() {
  local domain
  load_app
  domain="$(core_domain)"
  local address
  core "docker ps -a --filter name='^$NAME\$' --format 'Container: {{.Names}}  {{.Status}}  image {{.Image}}'
    [ -n \"\$(docker ps -aq --filter name='^$NAME\$')\" ] || echo 'Not installed on the Core.'"
  echo "App: $TITLE $(image)"
  address="$(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null || true")"
  [[ -z "$address" ]] || echo "Address on the Core: $address, port $PORT"
  echo "Needs: ${NEEDS:-nothing}"
  # The Core's database servers (shared by its apps), for apps that need a
  # given version
  if [[ " $NEEDS " == *" postgres "* ]]; then
    echo "The Core's PostgreSQL: $(core "docker exec postgresql postgres --version 2> /dev/null | sed -n 's/^postgres (PostgreSQL) \([^ ]*\).*/\1/p'")"
  fi
  if [[ " $NEEDS " == *" mysql "* ]]; then
    echo "The Core's MariaDB: $(core "docker exec pdnsmysql mariadb --version 2> /dev/null | sed -n 's/.* \([0-9][0-9.]*\)-MariaDB.*/\1/p'")"
  fi
  echo "URL: https://$NAME.$domain/"
}

cmd_logs() {
  load_app
  if [[ "${1:-}" == -f ]]; then
    core_tty "docker logs -f --tail 50 $NAME"
  else
    core "docker logs --tail 200 $NAME 2>&1"
  fi
}

cmd_shell() {
  load_app
  core "docker exec $NAME sh -c : > /dev/null 2>&1" \
    || die "Can't run a shell in $NAME: it isn't running (coreapp status, coreapp logs), or its image has no sh (images built FROM scratch or distroless). coreapp logs shows its output."
  if [[ $# -gt 0 ]]; then
    # One command, without a terminal, so scripts and agents can use it:
    # coreapp shell 'ls -l /data'
    core "docker exec $NAME sh -c $(printf '%q' "$*")"
  else
    core_tty "docker exec -it $NAME sh -c 'command -v bash > /dev/null && exec bash || exec sh'"
  fi
}

# --- signin -----------------------------------------------------------------

# The Core's test account (a person in its LDAP, made by coreapps
# test-account) gets a new random password each time, given to the Core and
# to signin.py on stdin, and kept nowhere
cmd_signin() {
  local path="" cookies="" form="" code=0 domain password account issuer client pkce
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --code) code=1 ;;
      --cookies)
        [[ $# -ge 2 ]] || die "--cookies needs a file: coreapp signin --cookies <file> [path]"
        cookies="$2"; shift ;;
      --form)
        [[ $# -ge 2 ]] || die "--form needs the form's action: coreapp signin --form /signin/core /signin"
        form="$2"; shift ;;
      --remove-account)
        init_core; sync_installer
        core "$REMOTE_INSTALLER/coreapps test-account --remove"
        return ;;
      /*) [[ -z "$path" ]] || die "One path: coreapp signin [path]"; path="$1" ;;
      *) die "coreapp signin [--cookies <file>] [--form <action>] [path], coreapp signin --code, or coreapp signin --remove-account (a path starts with /)" ;;
    esac
    shift
  done
  load_app
  [[ " $NEEDS " == *" sso "* ]] \
    || die "$NAME doesn't sign in with Core accounts (no \"sso\" in coreapp.toml's needs)."
  domain="$(core_domain)"
  sync_installer
  password="$(python3 -c 'import secrets; print(secrets.token_urlsafe(24))')"
  account="$(printf '%s' "$password" | core "$REMOTE_INSTALLER/coreapps test-account")" || exit 1
  echo "Signing in to $NAME as the Core's test account, $account:"
  if ((code)); then
    issuer="$(core "sed -n 's/^OIDC_ISSUER=//p' /federated/apps/$NAME/.env 2> /dev/null")"
    client="$(core "sed -n 's/^OIDC_CLIENT_ID=//p' /federated/apps/$NAME/.env 2> /dev/null")"
    [[ -n "$issuer" && -n "$client" ]] \
      || die "$NAME isn't installed on the Core with sign-in yet: coreapp deploy"
    pkce=()
    [[ "$SSO_PKCE" == true ]] && pkce=(--pkce)
    printf '%s' "$password" | python3 "$SIGNIN" --code "${pkce[@]}" \
      "$issuer" "$client" "https://$NAME.$domain$SSO_CALLBACK" "$account"
  else
    printf '%s' "$password" | python3 "$SIGNIN" ${cookies:+--cookies "$cookies"} ${form:+--form "$form"} \
      "https://$NAME.$domain${path:-/login}" "$account"
  fi
}

cmd_mail() {
  load_app
  [[ " $NEEDS " == *" email "* ]] \
    || die "$NAME doesn't send mail through the Core (no \"email\" in coreapp.toml's needs)."
  sync_installer
  core "$REMOTE_INSTALLER/coreapps mail $NAME"
}

cmd_core() {
  init_core
  sync_installer
  core "$REMOTE_INSTALLER/coreapps core"
}

cmd_remove() {
  local answer
  load_app
  echo "This uninstalls $NAME from the Core in '$VM', with its settings and data"
  echo "there${NEEDS:+ (and what it has in: $NEEDS)}. This folder stays as it is."
  read -r -p "Remove it? [y/N] " answer
  [[ "$answer" =~ ^[Yy] ]] || die "Not removed."
  sync_installer
  core "$REMOTE_INSTALLER/coreapps remove $NAME"
}

cmd_list() {
  init_core
  sync_installer
  core "$REMOTE_INSTALLER/coreapps list"
}

# --- install, update (published apps) -----------------------------------

cmd_install() {
  local source plan key value answer addon="" downgrade=""
  local -A info=()
  if [[ "${1:-}" == --downgrade ]]; then downgrade=--downgrade; shift; fi
  source="${1:-}"
  [[ $# -eq 1 && "$source" == https://* ]] \
    || die "Usage: coreapp install [--downgrade] <https://host/owner/repo>[@tag]   (default: its newest release)"
  init_core
  sync_installer
  echo "Reading $source..."
  plan="$(core "$REMOTE_INSTALLER/coreapps plan $downgrade $(printf '%q' "$source")")" || exit 1
  while IFS='=' read -r key value; do info[$key]="$value"; done <<< "$plan"

  echo
  echo "  ${info[title]} ${info[version]}${info[description]:+: ${info[description]}}"
  echo "  From:   ${info[source]} (${info[tag]}, commit ${info[commit]:0:12})"
  echo "  Image:  ${info[image]}:${info[version]}"
  echo "  Needs:  ${info[needs]:-nothing from the Core}"
  if [[ -n "${info[downgrade_from]:-}" ]]; then
    echo "  Goes back from the installed ${info[downgrade_from]}, keeping its settings and data,"
    echo "  which the older version may not understand."
  elif [[ "${info[state]}" == update ]]; then
    echo "  Updates the installed ${info[name]}, keeping its settings and data."
  else
    echo "  Installs it at ${info[url]}"
  fi
  echo
  if [[ "${info[addon]}" == yes ]]; then
    echo "This Core's tier is '${info[tier]}'. Installing records '${info[name]}' as an add-on"
    echo "app (ADDON_APPS in /etc/federated), which Federated may bill for."
    addon=--addon-ok
  fi
  read -r -p "Install it? [y/N] " answer
  [[ "$answer" =~ ^[Yy] ]] || die "Not installed."
  core "$REMOTE_INSTALLER/coreapps install $addon $downgrade $(printf '%q' "$source")"
}

cmd_update() {
  local name="${1:-}"
  [[ $# -eq 1 && "$name" =~ ^[a-z][a-z0-9-]*$ ]] || die "Usage: coreapp update <name>"
  init_core
  sync_installer
  core "$REMOTE_INSTALLER/coreapps update $name"
}

cmd_login() {
  local host="${1:-}" user token
  [[ $# -eq 1 && "$host" =~ ^[a-z0-9][a-z0-9.:-]*$ ]] \
    || die "Usage: coreapp login <host>   (e.g. coreapp login gitea.federated.computer)"
  echo "The Core in '$VM' keeps this token to install private apps from $host:"
  echo "their repositories and images. For Gitea, make a token for it with read"
  echo "access to repositories and packages (Settings > Applications)."
  read -r -p "User on $host: " user
  [[ "$user" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "'$user' isn't a user name."
  read -r -s -p "Token: " token
  echo
  init_core
  sync_installer
  # On stdin, so it's never in a command line
  printf '%s\n' "$token" | core "$REMOTE_INSTALLER/coreapps login $host $user"
}

cmd_logout() {
  local host="${1:-}"
  [[ $# -eq 1 && "$host" =~ ^[a-z0-9][a-z0-9.:-]*$ ]] || die "Usage: coreapp logout <host>"
  init_core
  sync_installer
  core "$REMOTE_INSTALLER/coreapps logout $host"
}

cmd_logins() {
  init_core
  sync_installer
  core "$REMOTE_INSTALLER/coreapps logins"
}

# --- publish ----------------------------------------------------------------

# A registry image name from the repository's git remote, as a suggestion:
# https://host/Owner/Repo.git or git@host:Owner/Repo.git -> host/owner/repo
image_from_remote() {
  local url host path
  url="$(git remote get-url origin 2> /dev/null)" || return 1
  case "$url" in
    https://*) url="${url#https://}"; host="${url%%/*}"; path="${url#*/}" ;;
    ssh://*) url="${url#ssh://}"; url="${url#*@}"; host="${url%%/*}"; host="${host%%:*}"; path="${url#*/}" ;;
    *@*:*) url="${url#*@}"; host="${url%%:*}"; path="${url#*:}" ;;
    *) return 1 ;;
  esac
  path="${path%.git}"
  [[ "$path" == */* ]] || return 1
  echo "$host/${path,,}"
}

cmd_publish() {
  local platform=linux/amd64 ref tag registry source="" commit check digest suggestion
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --platform) platform="${2:?--platform needs a value, e.g. linux/amd64,linux/arm64}"; shift ;;
      *) die "Usage: coreapp publish [--platform linux/amd64[,linux/arm64]]" ;;
    esac
    shift
  done
  load_manifest
  ref="$(image)"
  tag="v$VERSION"
  registry="${IMAGE%%/*}"

  if [[ "$IMAGE" == localhost/* ]]; then
    suggestion="$(image_from_remote || true)"
    if [[ -n "$suggestion" ]]; then
      suggestion=", e.g. image = \"$suggestion\" (from the git remote)"
    fi
    die "image = \"$IMAGE\" in coreapp.toml only exists where coreapp deploy copies it.
To publish, set image to your registry$suggestion.
coreapp deploy keeps working with that name."
  fi

  # A release is a commit: the image is built from it, and the Core installs
  # the app from the repository at its tag
  git rev-parse --is-inside-work-tree > /dev/null 2>&1 \
    || die "This folder isn't a git repository. A published app is one (its tag is the release)."
  [[ -z "$(git status --porcelain)" ]] \
    || die "There are uncommitted changes (git status). Commit them first, so the release matches a commit."
  # The Core reads icon.png from the repository at the tag
  [[ "$ICON" != bad ]] || die "$ICON_NOTE Fix it before publishing: a release can't be changed."
  if [[ "$ICON" == ok ]] && ! git ls-files -s icon.png | grep -q '^100644 '; then
    die "icon.png isn't in the repository (is it in .gitignore?), so Cores would show the default icon. Commit it first."
  fi
  [[ -z "$ICON_NOTE" ]] || echo "Note: $ICON_NOTE"
  commit="$(git rev-parse HEAD)"
  if git rev-parse -q --verify "refs/tags/$tag" > /dev/null; then
    [[ "$(git rev-parse "$tag^{commit}")" == "$commit" ]] \
      || die "The tag $tag already exists on another commit. Raise version in coreapp.toml for a new release."
  fi
  case "$(git remote get-url origin 2> /dev/null || true)" in
    https://*) source="$(git remote get-url origin)"; source="${source%.git}" ;;
  esac

  # Never replace a published version: Cores may have installed it
  echo "Checking $registry for $ref..."
  # (Only "not found" means it isn't there; any other error stops here)
  if check="$(docker buildx imagetools inspect "$ref" 2>&1)"; then
    die "$ref is already published. Raise version in coreapp.toml for a new release."
  fi
  case "$check" in
    *"not found"* | *"manifest unknown"*) ;;
    *unauthorized* | *denied* | *"authentication required"* | *401* | *403*)
      die "$registry wants you to log in first: docker login $registry
(For Gitea, use a token with the write:package scope as the password.)" ;;
    *) die "Couldn't check $registry for $ref: $check" ;;
  esac

  echo "Building $ref for $platform..."
  local labels=(--label "org.opencontainers.image.version=$VERSION"
    --label "org.opencontainers.image.revision=$commit"
    --label "org.opencontainers.image.title=$TITLE")
  [[ -n "$source" ]] && labels+=(--label "org.opencontainers.image.source=$source")
  if [[ "$platform" == *,* ]]; then
    # Several platforms at once can only be pushed straight from buildx
    docker buildx build --platform "$platform" "${labels[@]}" -t "$ref" --push . \
      || die "Building or pushing failed (above). Several platforms need a buildx builder that supports them: docker buildx create --use"
  else
    docker build -q --platform "$platform" "${labels[@]}" -t "$ref" . > /dev/null
    echo "Pushing it..."
    docker push -q "$ref" > /dev/null \
      || die "Pushing failed. Log in first if you haven't: docker login $registry"
  fi
  digest="$(docker buildx imagetools inspect "$ref" --format '{{.Manifest.Digest}}' 2> /dev/null || true)"

  git rev-parse -q --verify "refs/tags/$tag" > /dev/null || git tag -a "$tag" -m "${TITLE} $VERSION"
  echo "Published $ref${digest:+ ($digest)}."
  echo "Tagged this commit $tag. Push the commit and the tag, so the release is in the repository:"
  echo "  git push && git push origin $tag"
}

cmd="${1:-help}"
[[ $# -gt 0 ]] && shift
case "$cmd" in
  new) cmd_new "$@" ;;
  deploy) cmd_deploy "$@" ;;
  check) cmd_check ;;
  status) cmd_status ;;
  logs) cmd_logs "$@" ;;
  shell) cmd_shell "$@" ;;
  signin) cmd_signin "$@" ;;
  core) cmd_core ;;
  mail) cmd_mail ;;
  remove | rm) cmd_remove ;;
  list | ls) cmd_list ;;
  publish) cmd_publish "$@" ;;
  install) cmd_install "$@" ;;
  update) cmd_update "$@" ;;
  login) cmd_login "$@" ;;
  logout) cmd_logout "$@" ;;
  logins) cmd_logins ;;
  help | -h | --help) usage ;;
  *) usage >&2; exit 1 ;;
esac
