#!/usr/bin/env bash
# scalpanelctl: install, update and operate an all-in-one ScalPanel server
# (ADR-0063). Installed as /usr/local/sbin/scalpanelctl (vpanelctl is a link
# to it); runs as root.
#
#   scalpanelctl status                 versions and service state
#   scalpanelctl update [--yes]         install the latest release of the channel
#   scalpanelctl update --from-request  what the panel asked for (systemd path unit)
#   scalpanelctl runtime install <id>.. PHP versions from the runtime catalog (php-8.6 ...)
#   scalpanelctl runtime list           the catalog and what is installed
#   scalpanelctl compose <args>         docker compose for this installation
#   scalpanelctl admin <args>           scalpanel-admin in the control-plane image
#   scalpanelctl logs <service>         follow a service's log
#   scalpanelctl set-hostname <name>    change the panel hostname (certificate follows)
#   scalpanelctl set-ip <address>       the server's public IPv4 address changed
#   scalpanelctl mail-volume-cleanup    empty the old mail-store volume now (after the move)
#   scalpanelctl restart <service>..    restart platform services and wait until healthy
#   scalpanelctl reload-edge            reload the node's edge nginx (its configuration as is)
#   scalpanelctl node-bundle < bundle   re-enroll node-1 with a bundle from Servers → Nodes
#   scalpanelctl link init|add|remove|list   the private link to nodes on other servers
#   scalpanelctl cleanup                remove images no container uses (old releases)
#   scalpanelctl move-layout            move a vPanel server to the ScalPanel names now
#   scalpanelctl move-names             move the databases and volumes to the ScalPanel names now
#   scalpanelctl addon install scalguard --email <e-mail>
#                                       ScalGuard from its signed release (ADR-0177)
#   scalpanelctl addon uninstall scalguard [--delete-data]
#   scalpanelctl install                first installation (run by install.sh)
#
# Every file comes from the release site and is checked against the release
# key embedded below (via the signed channel and release descriptors) before
# it is used; only versions newer than the installed one are installed.
set -euo pipefail
umask 027
# Settings by their names from before the rename (VPANEL_*, ADR-0201).
for _v in $(compgen -v VPANEL_); do
  _n=SCALPANEL_${_v#VPANEL_}
  [ -n "${!_n:-}" ] || export "$_n=${!_v}"
done

RELEASE_PUBLIC_KEY="sprk1.QUorqm4dmqc5VKSD6_KfNN9erY0Go0bhP2NcrIYNilA"
UPDATE_URL_DEFAULT="https://scalpanel.scalws.com"

# The server's directories (ADR-0174). A server installed before the rename
# has the old ones (/etc/vpanel is a directory, not the link left by the
# move) until layout_move has run; every path below follows set_layout.
OLD_ETC=/etc/vpanel OLD_LIB=/var/lib/vpanel OLD_OPT=/opt/vpanel OLD_SRV=/srv/vpanel
NEW_ETC=/etc/scalpanel NEW_LIB=/var/lib/scalpanel NEW_OPT=/opt/scalpanel NEW_SRV=/srv/scalpanel
# (A mounted /etc/vpanel stays a directory: /etc/scalpanel then links to it.)
old_layout() { [ -d "$OLD_ETC" ] && [ ! -L "$OLD_ETC" ] && [ ! -e "$NEW_ETC" ]; }
# Set while the move runs; the next run finishes it (ADR-0174).
MOVING=/etc/.scalpanel-moving
set_layout() {
  if old_layout; then
    ETC=$OLD_ETC LIB=$OLD_LIB OPT=$OLD_OPT SRV=$OLD_SRV
    PROJECT=vpanel ENV_FILE=$OLD_ETC/vpanel.env LOCK=/run/vpanel-update.lock
  else
    ETC=$NEW_ETC LIB=$NEW_LIB OPT=$NEW_OPT SRV=$NEW_SRV
    PROJECT=scalpanel ENV_FILE=$NEW_ETC/scalpanel.env LOCK=/run/scalpanel-update.lock
  fi
  UPDATE_DIR=$LIB/update
  # The updater's own output lives where the worker can only read: as root it
  # never writes, renames or reads through names the worker controls
  # (security audit 2026-10-07, F09).
  STATUS_DIR=$LIB/update-status
  # Runtimes installed from the runtime catalog (ADR-0109): their signed
  # manifests (read by the control plane) and their image references.
  RUNTIME_MANIFESTS=$ETC/release/runtimes
  RUNTIME_STATE=$LIB/state/runtimes
}
set_layout
CP_UID=10001

log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2; }
die() { log "error: $*"; status failed "$*"; exit 1; }

# ---------------------------------------------------------------- settings
setting() { # name default: the environment, then the server's settings file
  local v=${!1:-}
  # Its name from before the rename (VPANEL_*) until rename_settings ran.
  [ -z "$v" ] && [ -r "$ENV_FILE" ] && v=$(sed -n -e "s/^$1=//p" -e "s/^VPANEL_${1#SCALPANEL_}=//p" "$ENV_FILE" | tail -1)
  printf '%s' "${v:-$2}"
}

# The server's settings file takes the ScalPanel names (ADR-0201) once the
# active release reads them, and never while an update runs: a failed one
# goes back to a release that knows only the old names.
rename_settings() {
  [ -w "$ENV_FILE" ] && grep -q '^VPANEL_' "$ENV_FILE" || return 0
  grep -q 'SCALPANEL_HOSTNAME:-' "$OPT/current/compose.yaml" 2>/dev/null || return 0
  (
    flock -n 8 || exit 0
    sed -i -e 's/^VPANEL_/SCALPANEL_/' "$ENV_FILE"
    log "settings renamed to the ScalPanel names in $ENV_FILE"
  ) 8>"$LOCK"
}
# Release sites that moved: a server set to one of them follows the move
# (vpanel.scb.network, then releases.scalws.com, which ScalWS now uses).
OLD_UPDATE_URLS="https://vpanel.scb.network https://releases.scalws.com"
move_update_url() {
  local u
  [ -w "$ENV_FILE" ] || return 0
  for u in $OLD_UPDATE_URLS; do
    [ "$u" = "$UPDATE_URL_DEFAULT" ] && continue
    if grep -qxF "SCALPANEL_UPDATE_URL=$u" "$ENV_FILE"; then
      sed -i "s#^SCALPANEL_UPDATE_URL=$u\$#SCALPANEL_UPDATE_URL=$UPDATE_URL_DEFAULT#" "$ENV_FILE"
      log "release site moved: $u -> $UPDATE_URL_DEFAULT"
    fi
  done
}
move_update_url
UPDATE_URL=$(setting SCALPANEL_UPDATE_URL "$UPDATE_URL_DEFAULT")
CHANNEL=$(setting SCALPANEL_UPDATE_CHANNEL stable)
# The databases' and their roles' names (ADR-0201): "scalpanel", or "vpanel"
# on a server installed before the rename until names_move has run.
NAMES=$(setting SCALPANEL_NAMES vpanel)
case "$NAMES" in scalpanel|vpanel) ;; *) NAMES=vpanel ;; esac
installed_version() { cat "$ETC/version" 2>/dev/null || echo none; }

# The updater's progress, read by the worker (ADR-0063): status.json for
# updates, runtime-status.json for runtime installations (ADR-0109).
# The optional percent is the whole operation's progress (0-100).
STATUS_VERSION=""
STATUS_FILE=status.json
status() { # state message [percent]
  [ -d "$UPDATE_DIR" ] || return 0
  install -d -o root -g root -m 0755 "$STATUS_DIR" || return 0
  local msg=${2//\\/\\\\}
  msg=${msg//\"/\\\"}
  msg=$(printf '%s' "$msg" | tr '\n\r\t' '   ' | cut -c1-1500)
  local tmp
  tmp=$(mktemp "$STATUS_DIR/.status.XXXXXX") || return 0
  local pct=""
  [[ "${3:-}" =~ ^[0-9]+$ ]] && [ "$3" -le 100 ] && pct=",\"progress\":$3"
  printf '{"state":"%s","version":"%s","current":"%s","message":"%s","updated_at":"%s"%s}\n' \
    "$1" "$STATUS_VERSION" "$(installed_version)" "$msg" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$pct" > "$tmp"
  chmod 0644 "$tmp"
  mv -fT "$tmp" "$STATUS_DIR/$STATUS_FILE"
}

# ---------------------------------------------------------------- verification
# The release key is ed25519 ("sprk1." + base64url of the 32-byte key); openssl
# 3 verifies its signatures over the raw file.
pubkey_pem() {
  # The DER header of an ed25519 key is 12 bytes, a multiple of 3: its
  # base64 ("MCowBQYDK2VwAyEA") and the key's simply concatenate.
  local b64=${RELEASE_PUBLIC_KEY#*.}
  b64=$(printf '%s' "$b64" | tr '_-' '/+')
  while [ $(( ${#b64} % 4 )) -ne 0 ]; do b64="$b64="; done
  [ ${#b64} -eq 44 ] || die "the embedded release key is invalid"
  printf -- '-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA%s\n-----END PUBLIC KEY-----\n' "$b64" > "$WORK/release.pem"
  openssl pkey -pubin -in "$WORK/release.pem" -noout 2>/dev/null || die "openssl cannot read the release key"
}

verify() { # file (signature in file.sig)
  base64 -d "$1.sig" > "$WORK/sig.bin" 2>/dev/null || return 1
  openssl pkeyutl -verify -pubin -inkey "$WORK/release.pem" -rawin -in "$1" -sigfile "$WORK/sig.bin" >/dev/null 2>&1
}

fetch() { # path dest (plain HTTP only for testing, SCALPANEL_ALLOW_HTTP=1)
  local proto="=https"
  [ "$(setting SCALPANEL_ALLOW_HTTP 0)" = 1 ] && proto="=http,https"
  curl -fsSL --proto "$proto" --retry 3 --retry-delay 2 --connect-timeout 20 -o "$2" "$UPDATE_URL/$1"
}

fetch_signed() { # path dest
  fetch "$1" "$2" || return 1
  fetch "$1.sig" "$2.sig" || return 1
  verify "$2" || die "the signature of $1 does not verify: refusing to continue"
}

sha256_of() { sha256sum "$1" | cut -d' ' -f1; }

json() { jq -er "$1" "$2"; }

version_gt() { # a b: is a newer than b?
  [ "$2" = none ] && return 0
  [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -1)" = "$1" ] && [ "$1" != "$2" ]
}

# ---------------------------------------------------------------- compose
# The host paths in compose.yaml come from SCALPANEL_ETC/LIB/SRV; a moved
# server's volumes keep their old names through compose.volumes.yaml.
compose() {
  local over=()
  # The edge's access logs, on the host for tools such as ScalGuard (ADR-0176).
  install -d -m 0750 "$LIB/edge-logs"
  [ -s "$ETC/compose.volumes.yaml" ] && over=(-f "$ETC/compose.volumes.yaml")
  # The ScalGuard add-on's services (ADR-0177), once installed. Its image
  # was loaded, not pulled: no pull may ask a registry for it (an override
  # from 0.1.25 lacks this).
  if [ -s "$ETC/compose.scalguard.yaml" ]; then
    grep -q '^    pull_policy: never$' "$ETC/compose.scalguard.yaml" ||
      sed -i '/^  scalguard-control:$/,/^    image: /s/^\(    image: .*\)$/\1\n    pull_policy: never/' "$ETC/compose.scalguard.yaml"
    over+=(-f "$ETC/compose.scalguard.yaml")
  fi
  # The private link to nodes on other servers (ADR-0232), once set up.
  [ -s "$ETC/compose.link.yaml" ] && over+=(-f "$ETC/compose.link.yaml")
  SCALPANEL_ETC=$ETC SCALPANEL_LIB=$LIB SCALPANEL_SRV=$SRV \
    docker compose --project-name "$PROJECT" --project-directory "$OPT/current" -f "$OPT/current/compose.yaml" "${over[@]}" \
    --env-file "$ETC/release.env" --env-file "$ENV_FILE" "$@"
}

# One value from the control-plane database.
sql() {
  compose exec -T postgres psql -U "$NAMES" -d "$NAMES" -tAc "$1"
}

# Runs scalpanel-admin with the control plane's configuration.
admin() {
  compose run --rm --no-deps -T migrate scalpanel-admin "$@"
}

# ---------------------------------------------------------------- release
# Downloads and verifies a release: channel -> descriptor -> bundle and
# registry files. Sets RELEASE_VERSION and RELEASE_DIR.
download_release() { # [version]
  fetch_signed "channels/$CHANNEL.json" "$WORK/channel.json" || die "cannot read the $CHANNEL channel from $UPDATE_URL"
  # A signed file of another channel is not this one (security audit run-6).
  [ "$(json .channel "$WORK/channel.json")" = "$CHANNEL" ] || die "the $CHANNEL channel file names another channel"
  local want=${1:-}
  local latest
  latest=$(json .version "$WORK/channel.json")
  [ -z "$want" ] && want=$latest
  [ "$want" = "$latest" ] || die "$want is not the latest release of the $CHANNEL channel ($latest)"
  local rel
  rel=$(json .release "$WORK/channel.json")
  case "$rel" in *..*|/*|*://*) die "invalid release path" ;; esac
  fetch_signed "$rel" "$WORK/release.json" || die "cannot read the release descriptor"
  RELEASE_VERSION=$(json .version "$WORK/release.json")
  [ "$RELEASE_VERSION" = "$want" ] || die "the descriptor is for $RELEASE_VERSION, not $want"
  local min
  min=$(jq -r '.min_version // ""' "$WORK/release.json")
  if [ -n "$min" ] && [ "$(installed_version)" != none ] && version_gt "$min" "$(installed_version)"; then
    die "$RELEASE_VERSION needs $min or newer installed first"
  fi
  STATUS_VERSION=$RELEASE_VERSION
  status downloading "downloading ScalPanel $RELEASE_VERSION" 0
  local base=${rel%/*}
  RELEASE_DIR=$OPT/releases/$RELEASE_VERSION
  # The bundle: compose, scripts, host tools.
  fetch "$(json .bundle.path "$WORK/release.json")" "$WORK/bundle.tar.gz" || die "cannot download the bundle"
  [ "$(sha256_of "$WORK/bundle.tar.gz")" = "$(json .bundle.sha256 "$WORK/release.json")" ] || die "the bundle does not match the release"
  rm -rf "$RELEASE_DIR.new" && mkdir -p "$RELEASE_DIR.new"
  tar -xzf "$WORK/bundle.tar.gz" -C "$RELEASE_DIR.new" --no-same-owner
  cp "$WORK/release.json" "$WORK/release.json.sig" "$RELEASE_DIR.new/"
  rm -rf "$RELEASE_DIR" && mv "$RELEASE_DIR.new" "$RELEASE_DIR"
  # The images: only registry files this server does not have yet.
  fetch "$(json .registry_files.path "$WORK/release.json")" "$WORK/registry-files.txt" || die "cannot download the registry file list"
  [ "$(sha256_of "$WORK/registry-files.txt")" = "$(json .registry_files.sha256 "$WORK/release.json")" ] || die "the registry file list does not match the release"
  sync_registry "$WORK/registry-files.txt"
  : "$base"
}

# Registry storage files: "<sha256> <size> <path>" per line, paths below
# docker/registry/v2/. Present files with the right digest are kept. The
# progress goes from SYNC_FROM to SYNC_TO percent by the bytes downloaded.
sync_registry() { # list
  local list=$1 total missing=0 n=0 bytes got=0 pct last=-1 from=${SYNC_FROM:-5} to=${SYNC_TO:-80}
  mkdir -p "$LIB/registry"
  total=$(wc -l < "$list")
  while read -r sum size path; do
    case "$path" in docker/registry/v2/*) ;; *) die "invalid registry path $path" ;; esac
    case "$path" in *..*) die "invalid registry path $path" ;; esac
    [[ "$sum" =~ ^[0-9a-f]{64}$ ]] || die "invalid digest in the registry list"
    local dst="$LIB/registry/$path"
    if [ -f "$dst" ] && [ "$(stat -c %s "$dst")" = "$size" ]; then
      case "$path" in
        */blobs/sha256/*/data) continue ;;  # content-addressed: the path is the digest
        *) [ "$(sha256_of "$dst")" = "$sum" ] && continue ;;
      esac
    fi
    [[ "$size" =~ ^[0-9]+$ ]] || die "invalid size in the registry list"
    printf '%s %s %s\n' "$sum" "$size" "$path"
  done < "$list" > "$WORK/registry-missing.txt"
  missing=$(wc -l < "$WORK/registry-missing.txt")
  bytes=$(awk '{s += $2} END {printf "%d", s}' "$WORK/registry-missing.txt")
  log "registry: $missing of $total files to download"
  need_space "$bytes" "${SYNC_LABEL:-ScalPanel $RELEASE_VERSION}"
  while read -r sum size path; do
    n=$((n + 1))
    local dst="$LIB/registry/$path"
    mkdir -p "$(dirname "$dst")"
    fetch "registry/$path" "$dst.part" || die "cannot download $path"
    [ "$(sha256_of "$dst.part")" = "$sum" ] || { rm -f "$dst.part"; die "$path does not match the release"; }
    mv "$dst.part" "$dst"
    got=$((got + size))
    pct=$((from + (to - from) * got / (bytes > 0 ? bytes : 1)))
    if [ "$pct" != "$last" ] || [ $((n % 20)) -eq 0 ]; then
      last=$pct
      status downloading "downloading ${SYNC_LABEL:-ScalPanel $RELEASE_VERSION}: $n of $missing files" "$pct"
    fi
  done < "$WORK/registry-missing.txt"
  return 0
}

# Writes $ETC/release.env from a release dir: the release's images,
# and the runtimes installed from the catalog that the release lacks.
write_release_env() { # release dir
  local d=$1
  img() { jq -er --arg n "$1" '.images[$n]' "$d/release.json"; }
  local runtimes="" n f id ref
  for n in $(jq -r '.images | keys[] | select(startswith("runtime:"))' "$d/release.json"); do
    runtimes="$runtimes,${n#runtime:}=registry:5000/$(img "$n")"
  done
  for f in "$RUNTIME_STATE"/*; do
    [ -f "$f" ] || continue
    id=$(basename "$f")
    runtime_id_ok "$id" || continue
    case ",$runtimes" in *",$id="*) continue ;; esac
    [ -s "$RUNTIME_MANIFESTS/$id.json" ] || continue
    ref=$(head -c 300 "$f")
    image_ok "$ref" || continue
    runtimes="$runtimes,$id=registry:5000/$ref"
  done
  {
    echo "# Written by scalpanelctl for ScalPanel $(json .version "$d/release.json"); do not edit."
    echo "SCALPANEL_IMAGE_CONTROLPLANE=127.0.0.1:5000/$(img controlplane)"
    echo "SCALPANEL_IMAGE_WEB=127.0.0.1:5000/$(img web)"
    echo "SCALPANEL_IMAGE_NODE=127.0.0.1:5000/$(img node)"
    echo "SCALPANEL_IMAGE_MAIL=127.0.0.1:5000/$(img mail)"
    echo "SCALPANEL_SESSION_IMAGE=registry:5000/$(img session)"
    echo "SCALPANEL_RUNTIME_IMAGES=${runtimes#,}"
    echo "SCALPANEL_RELEASE_PUBLIC_KEY=$RELEASE_PUBLIC_KEY"
  } > "$ETC/release.env.new"
  mv "$ETC/release.env.new" "$ETC/release.env"
}

# Writes $ETC/release.env and $ETC/release from a release dir.
# The administrator's scripts (ADR-0171): /scripts follows the active
# release, unless the server already has a /scripts of its own. Also run on
# every vpanelctl command: an update from a release without scripts is
# activated by that release's vpanelctl.
scripts_link() {
  if [ -d "$OPT/current/scripts" ] && { [ -L /scripts ] || [ ! -e /scripts ]; } &&
    [ "$(readlink /scripts 2>/dev/null)" != "$OPT/current/scripts" ]; then
    ln -sfn "$OPT/current/scripts" /scripts
  fi
}

activate() { # release dir
  local d=$1
  install -d -m 0755 "$ETC/release"
  install -m 0644 "$d/release/manifest.json" "$ETC/release/manifest.json.new"
  install -m 0644 "$d/release/manifest.json.sig" "$ETC/release/manifest.json.sig.new"
  install -m 0644 "$d/release/cosign.pub" "$ETC/release/cosign.pub.new"
  for f in manifest.json manifest.json.sig cosign.pub; do mv "$ETC/release/$f.new" "$ETC/release/$f"; done
  install -d -m 0755 "$RUNTIME_MANIFESTS"
  write_release_env "$d"
  ln -sfn "$d" "$OPT/current.new" && mv -T "$OPT/current.new" "$OPT/current"
  install_ctl "$d"
  scripts_link
  install_units "$d"
}

# scalpanelctl; vpanelctl links to it only while the update unit from before
# the move (ADR-0174) still calls that name.
install_ctl() { # release dir
  install -m 0755 "$1/bin/scalpanelctl" /usr/local/sbin/scalpanelctl.new
  mv -f /usr/local/sbin/scalpanelctl.new /usr/local/sbin/scalpanelctl
  if old_layout; then
    ln -sfn scalpanelctl /usr/local/sbin/vpanelctl
  elif [ -L /usr/local/sbin/vpanelctl ]; then
    rm -f /usr/local/sbin/vpanelctl
  fi
}

# The update path unit (ADR-0063): scalpanel-update.*, or until the server
# moved to the ScalPanel names the vpanel-update.* that also starts the move
# (ADR-0174).
install_units() { # release dir
  local d=$1 u=/etc/systemd/system lib
  if old_layout; then
    install -m 0644 "$d/systemd/vpanel-update.path" "$d/systemd/vpanel-update.service" "$u/"
    # Back from a failed move: the old unit takes the requests again.
    if [ -e "$u/scalpanel-update.path" ]; then
      systemctl disable --now scalpanel-update.path >/dev/null 2>&1 || true
      rm -f "$u/scalpanel-update.path" "$u/scalpanel-update.service"
    fi
    systemctl daemon-reload 2>/dev/null || true
    systemctl enable vpanel-update.path >/dev/null 2>&1 || true
    # A path unit watches the paths it had when it started.
    systemctl restart vpanel-update.path 2>/dev/null || true
    return 0
  fi
  # A path unit watches real paths: where $LIB is a link, its target.
  lib=$(readlink -f "$LIB")
  sed "s#/var/lib/scalpanel/#$lib/#g" "$d/systemd/scalpanel-update.path" > "$u/scalpanel-update.path"
  install -m 0644 "$d/systemd/scalpanel-update.service" "$u/"
  chmod 0644 "$u/scalpanel-update.path"
  if [ -e "$u/vpanel-update.path" ]; then
    systemctl disable --now vpanel-update.path >/dev/null 2>&1 || true
    rm -f "$u/vpanel-update.path" "$u/vpanel-update.service"
  fi
  systemctl daemon-reload 2>/dev/null || true
  # Enabled by the installation (at its end) and by the move.
  if systemctl is-enabled --quiet scalpanel-update.path 2>/dev/null; then
    systemctl restart scalpanel-update.path 2>/dev/null || true
  fi
}

# The local MariaDB's provisioning account gains what later releases need
# (idempotent): PROCESS and CONNECTION ADMIN for the database processes page
# (ADR-0125), and the user-name database namespace (ADR-0145).
mariadb_grants() {
  [ -s "$ETC/secrets/mariadb-root" ] || return 0
  compose exec -T -e PROV="${NAMES}_prov" mariadb sh -c 'MYSQL_PWD="$(cat /run/scalpanel-db/mariadb-root 2>/dev/null || cat /run/vpanel-db/mariadb-root 2>/dev/null || printf %s "$MARIADB_ROOT_PASSWORD")" mariadb -uroot -e "GRANT PROCESS, CONNECTION ADMIN ON *.* TO '"'"'$PROV'"'"'@'"'"'%'"'"'"' >/dev/null 2>&1 ||
    log "MariaDB: the provisioning account could not be granted PROCESS and CONNECTION ADMIN; the database processes page shows only its own"
  # Database names start with the owner's user name (ADR-0145): the data
  # privileges cover every "prefix_name" (a literal underscore).
  compose exec -T -e PROV="${NAMES}_prov" mariadb sh -c 'MYSQL_PWD="$(cat /run/scalpanel-db/mariadb-root 2>/dev/null || cat /run/vpanel-db/mariadb-root 2>/dev/null || printf %s "$MARIADB_ROOT_PASSWORD")" mariadb -uroot -e "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, CREATE TEMPORARY TABLES, LOCK TABLES, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EXECUTE, EVENT, TRIGGER, REFERENCES ON \`%\\_%\`.* TO '"'"'$PROV'"'"'@'"'"'%'"'"' WITH GRANT OPTION"' >/dev/null 2>&1 ||
    log "MariaDB: the provisioning account could not be granted the customer namespace; new databases fail until it is (see ADR-0145)"
}

# The mail-store volume, kept after the mail store moved to the host's
# $SRV/mail (ADR-0147) in case of a rollback, is emptied once the move is
# two weeks old (now with "force"): only when the new store has every
# mailbox and the volume holds nothing newer than the move. Only servers
# installed as vPanel have it, under its vPanel name.
mail_volume_cleanup() { # [force]
  local mark=$SRV/mail/.scalpanel-store src old new
  # The mail server renames its marker (ADR-0201); until it ran, the old one.
  [ -e "$mark" ] || mark=$SRV/mail/.vpanel-store
  [ -e "$mark" ] || return 0
  if [ "${1:-}" != force ] && [ -z "$(find "$mark" -mtime +14 2>/dev/null)" ]; then return 0; fi
  src=$(docker volume inspect -f '{{.Mountpoint}}' scalpanel_mail-store 2>/dev/null ||
    docker volume inspect -f '{{.Mountpoint}}' vpanel_mail-store 2>/dev/null) || return 0
  [ -d "$src" ] && [ -n "$(ls -A "$src" 2>/dev/null)" ] || return 0
  if [ -n "$(find "$src" -newer "$mark" -type f -print -quit 2>/dev/null)" ]; then
    log "mail: the old mail-store volume has mail newer than the move; kept"; return 0
  fi
  old=$(find "$src" -mindepth 1 -maxdepth 1 -name 'mbx_*' | wc -l)
  new=$(find "$SRV/mail" -mindepth 1 -maxdepth 1 -name 'mbx_*' | wc -l)
  if [ "$new" -lt "$old" ]; then
    log "mail: $SRV/mail has fewer mailboxes ($new) than the old volume ($old); kept"; return 0
  fi
  log "mail: emptying the old mail-store volume ($old mailboxes are in $SRV/mail)"
  find "$src" -mindepth 1 -delete
}

# Mail directory upgrades (images/mail/upgrade): applied once each, in order.
mail_upgrades() { # release dir
  local d=$1 f
  mkdir -p "$LIB/state"
  touch "$LIB/state/mail-upgrades"
  for f in "$d"/mail/upgrade/*.sql; do
    [ -e "$f" ] || continue
    grep -qxF "$(basename "$f")" "$LIB/state/mail-upgrades" && continue
    log "mail directory: applying $(basename "$f")"
    compose exec -T mail-db psql -v ON_ERROR_STOP=1 -U mailadmin -d "${NAMES}_mail" < "$f" >/dev/null ||
      die "the mail directory upgrade $(basename "$f") failed"
    basename "$f" >> "$LIB/state/mail-upgrades"
  done
}

wait_healthy() { # timeout-seconds service...
  local deadline=$(( $(date +%s) + $1 )); shift
  local s st
  for s in "$@"; do
    while :; do
      st=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' \
        "$(compose ps -q "$s" 2>/dev/null | head -1)" 2>/dev/null || echo missing)
      [ "$st" = healthy ] || [ "$st" = running ] && break
      [ "$(date +%s)" -lt "$deadline" ] || return 1
      sleep 3
    done
  done
}

# ---------------------------------------------------------------- runtimes
# New PHP versions between releases (ADR-0109). runtimes/catalog.json is
# signed with the release key; each entry names one image, its own signed
# manifest (approving that image for that runtime only) and its registry
# files, each by SHA-256.
runtime_id_ok() { [[ "$1" =~ ^php-[89]\.(0|[1-9][0-9]?)$ ]]; }
# Runtimes published before the rename keep their repository (ADR-0201).
image_ok() { [[ "$1" =~ ^(scalpanel|vpanel)/[a-z0-9][a-z0-9._-]{0,100}@sha256:[0-9a-f]{64}$ ]]; }
artifact_ok() { # path sha256
  [[ "$1" =~ ^[a-z0-9][a-z0-9._/-]{0,200}$ ]] && [[ "$1" != *..* ]] && [[ "$2" =~ ^[0-9a-f]{64}$ ]]
}

# Downloads and verifies one runtime into $WORK/rt/<id> without changing
# the installation: its manifest and signature, image reference, release
# time and name. Its registry files land in the registry storage
# (content-addressed; nothing refers to them until the runtime is placed).
stage_runtime() { # id n total
  local id=$1 n=$2 total=$3 d="$WORK/rt/$1"
  runtime_id_ok "$id" || die "invalid runtime $id"
  STATUS_VERSION=$id
  SYNC_LABEL="$id ($n of $total)"
  jq -e --arg id "$id" '.runtimes | map(select(.id == $id)) | length == 1' "$WORK/catalog.json" >/dev/null ||
    die "$id is not in the runtime catalog"
  mkdir -p "$d"
  jq --arg id "$id" '.runtimes[] | select(.id == $id)' "$WORK/catalog.json" > "$d/entry.json"
  local min image mpath msum lpath lsum
  min=$(jq -r '.min_version // ""' "$d/entry.json")
  if [ -n "$min" ] && version_gt "$min" "$(installed_version)"; then
    die "$id needs ScalPanel $min or newer; update first"
  fi
  image=$(json .image "$d/entry.json"); image_ok "$image" || die "invalid image for $id"
  # A runtime of the release is rebuilt with releases. An installed catalog
  # runtime is replaced only by a different image released later (a
  # rebuild, e.g. a PHP patch release): an older signed entry served again
  # is refused.
  local released prev=""
  released=$(json .released_at "$d/entry.json")
  [[ "$released" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] || die "invalid release time for $id"
  if [ -f "$RUNTIME_STATE/$id" ]; then
    [ "$(head -c 300 "$RUNTIME_STATE/$id")" != "$image" ] || die "$id is installed already"
    prev=$(head -c 40 "$RUNTIME_STATE/$id.released" 2>/dev/null || true)
    [ -z "$prev" ] || [[ "$released" > "$prev" ]] || die "the catalog's $id is not newer than the installed one"
  elif grep -qE "[=,]$id=" "$ETC/release.env" 2>/dev/null; then
    die "$id comes with this ScalPanel release"
  fi
  mpath=$(json .manifest.path "$d/entry.json"); msum=$(json .manifest.sha256 "$d/entry.json")
  lpath=$(json .registry_files.path "$d/entry.json"); lsum=$(json .registry_files.sha256 "$d/entry.json")
  artifact_ok "$mpath" "$msum" && artifact_ok "$lpath" "$lsum" || die "invalid files for $id"
  status downloading "downloading $id ($n of $total)"
  # The runtime's manifest: signed itself, and the one the catalog names.
  fetch_signed "$mpath" "$d/manifest.json" || die "cannot read the manifest of $id"
  [ "$(sha256_of "$d/manifest.json")" = "$msum" ] || die "the manifest of $id does not match the catalog"
  jq -e --arg id "$id" --arg ref "registry:5000/$image" \
    '.version == $id and (.images | length) == 1 and .images[$id] == $ref' "$d/manifest.json" >/dev/null ||
    die "the manifest of $id does not approve its image"
  fetch "$lpath" "$d/registry-files.txt" || die "cannot download the registry file list of $id"
  [ "$(sha256_of "$d/registry-files.txt")" = "$lsum" ] || die "the registry file list of $id does not match the catalog"
  sync_registry "$d/registry-files.txt"
  printf '%s' "$image" > "$d/image"
  printf '%s' "$released" > "$d/released"
  json .name "$d/entry.json" > "$d/name"
}

# Installs runtimes of the catalog together (ADR-0109, ADR-0110): all are
# downloaded and verified first, then placed at once and the control plane
# restarts once; if it does not come back, every one goes back.
install_runtimes() { # id...
  local total=$# n=0 id f names=""
  STATUS_FILE=runtime-status.json
  STATUS_VERSION=$1
  pubkey_pem
  fetch_signed runtimes/catalog.json "$WORK/catalog.json" || die "cannot read the runtime catalog from $UPDATE_URL"
  for id in "$@"; do
    n=$((n + 1))
    stage_runtime "$id" "$n" "$total"
  done
  status installing "installing $*"
  cp "$ETC/release.env" "$WORK/release.env.previous"
  install -d -m 0755 "$RUNTIME_MANIFESTS"
  install -d -m 0700 "$RUNTIME_STATE"
  # What a failed start goes back to (nothing, for a new runtime).
  mkdir -p "$WORK/previous/manifests" "$WORK/previous/state"
  for id in "$@"; do
    for f in "$RUNTIME_MANIFESTS/$id.json" "$RUNTIME_MANIFESTS/$id.json.sig"; do [ -f "$f" ] && cp -p "$f" "$WORK/previous/manifests/"; done
    for f in "$RUNTIME_STATE/$id" "$RUNTIME_STATE/$id.released"; do [ -f "$f" ] && cp -p "$f" "$WORK/previous/state/"; done
  done
  for id in "$@"; do
    install -m 0644 "$WORK/rt/$id/manifest.json" "$RUNTIME_MANIFESTS/$id.json.new"
    install -m 0644 "$WORK/rt/$id/manifest.json.sig" "$RUNTIME_MANIFESTS/$id.json.sig.new"
    mv "$RUNTIME_MANIFESTS/$id.json.sig.new" "$RUNTIME_MANIFESTS/$id.json.sig"
    mv "$RUNTIME_MANIFESTS/$id.json.new" "$RUNTIME_MANIFESTS/$id.json"
    cp "$WORK/rt/$id/image" "$RUNTIME_STATE/$id"
    cp "$WORK/rt/$id/released" "$RUNTIME_STATE/$id.released"
    names="$names, $(cat "$WORK/rt/$id/name")"
  done
  write_release_env "$(readlink -f "$OPT/current")"
  # The api and worker read the image catalog at start; nodes pull the
  # image from the local registry when a website first uses it.
  compose up -d api worker || true
  if ! wait_healthy 300 api worker; then
    log "the control plane did not start with $*; going back"
    for id in "$@"; do
      rm -f "$RUNTIME_MANIFESTS/$id.json" "$RUNTIME_MANIFESTS/$id.json.sig" "$RUNTIME_STATE/$id" "$RUNTIME_STATE/$id.released"
    done
    for f in "$WORK"/previous/manifests/*; do [ -f "$f" ] && cp -p "$f" "$RUNTIME_MANIFESTS/"; done
    for f in "$WORK"/previous/state/*; do [ -f "$f" ] && cp -p "$f" "$RUNTIME_STATE/"; done
    cp "$WORK/release.env.previous" "$ETC/release.env"
    compose up -d api worker || true
    die "the control plane did not start with $*; the previous state was restored"
  fi
  STATUS_VERSION=${!#}
  status "done" "${names#, } installed"
  log "$* installed"
}

cmd_runtime() {
  local sub=${1:-list}
  exec 9>"$LOCK"
  flock -n 9 || { log "an update or installation is running"; exit 1; }
  WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
  case "$sub" in
    install)
      shift
      [ $# -ge 1 ] && [ $# -le 10 ] || die "usage: scalpanelctl runtime install <id>..."
      install_runtimes "$@" ;;
    list)
      pubkey_pem
      fetch_signed runtimes/catalog.json "$WORK/catalog.json" || die "cannot read the runtime catalog"
      local id
      for id in $(jq -r '.runtimes[].id' "$WORK/catalog.json"); do
        runtime_id_ok "$id" || continue
        if grep -qE "[=,]$id=" "$ETC/release.env" 2>/dev/null; then echo "$id installed"; else echo "$id available"; fi
      done ;;
    *) die "usage: scalpanelctl runtime install <id>... | list" ;;
  esac
}

# The panel's runtime request (ADR-0109), taken like an update request:
# "runtimes" (ADR-0110) or, from older workers, "runtime".
runtime_from_request() {
  install -d -o root -g root -m 0755 "$STATUS_DIR"
  local req="$STATUS_DIR/.runtime-request.$$" id ids=()
  mv -fT -- "$UPDATE_DIR/runtime-request.json" "$req" 2>/dev/null || return 0
  if [ -L "$req" ] || [ ! -f "$req" ] || [ "$(stat -c %s "$req")" -gt 4096 ]; then rm -f -- "$req"; return 0; fi
  local list
  list=$(jq -er 'if (.runtimes | type) == "array" and (.runtimes | length) > 0 then .runtimes[] else .runtime end' < "$req" 2>/dev/null) ||
    { rm -f -- "$req"; return 0; }
  rm -f -- "$req"
  for id in $list; do
    runtime_id_ok "$id" || return 0
    case " ${ids[*]} " in *" $id "*) continue ;; esac
    ids+=("$id")
  done
  [ ${#ids[@]} -ge 1 ] && [ ${#ids[@]} -le 10 ] || return 0
  # In a subshell: a failure (die) ends that installation only.
  ( WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT; install_runtimes "${ids[@]}" ) || true
}

# ---------------------------------------------------------------- services
# Restarts from the Service Status page (ADR-0111): only these compose
# services, the same list as the control plane's.
service_ok() {
  case "$1" in
    api|worker|panel|node|postgres|mariadb|pdns|mail|mail-db|webmail-api|sshgw|backup-store) return 0 ;;
  esac
  return 1
}

restart_services() { # service...
  STATUS_FILE=service-status.json
  STATUS_VERSION="$*"
  status installing "restarting $*"
  local s failed=""
  for s in "$@"; do
    log "restarting $s"
    compose restart "$s" >/dev/null 2>&1 || failed="$failed $s"
  done
  [ -z "$failed" ] || die "these services could not be restarted:$failed"
  if ! wait_healthy 300 "$@"; then
    die "restarted, but not healthy within 5 minutes: $*; see scalpanelctl status"
  fi
  status "done" "restarted: $*"
}

# The panel's restart request, taken like an update request.
service_from_request() {
  install -d -o root -g root -m 0755 "$STATUS_DIR"
  local req="$STATUS_DIR/.service-request.$$" list s ids=()
  mv -fT -- "$UPDATE_DIR/service-request.json" "$req" 2>/dev/null || return 0
  if [ -L "$req" ] || [ ! -f "$req" ] || [ "$(stat -c %s "$req")" -gt 4096 ]; then rm -f -- "$req"; return 0; fi
  if ! jq -e '.action == "restart" and (.services | type) == "array"' < "$req" >/dev/null 2>&1; then rm -f -- "$req"; return 0; fi
  list=$(jq -r '.services[]' < "$req" 2>/dev/null) || { rm -f -- "$req"; return 0; }
  rm -f -- "$req"
  for s in $list; do
    service_ok "$s" || return 0
    case " ${ids[*]} " in *" $s "*) continue ;; esac
    ids+=("$s")
  done
  [ ${#ids[@]} -ge 1 ] || return 0
  # In a subshell: a failure (die) ends that request only.
  ( restart_services "${ids[@]}" ) || true
}

# ---------------------------------------------------------------- update
cmd_update() {
  local yes=0 from_request=0 want=""
  for a in "$@"; do
    case "$a" in
      --yes|-y) yes=1 ;;
      --from-request) from_request=1; yes=1 ;;
      *) want=$a ;;
    esac
  done
  exec 9>"$LOCK"
  # A request waits for a running update (its file stays until handled, and
  # a service that exits at once would be started again and again).
  if [ $from_request = 1 ]; then
    flock -w 3600 9 || { log "another update is still running"; exit 0; }
  else
    flock -n 9 || { log "another update is running"; exit 0; }
  fi
  if [ $from_request = 1 ]; then
    service_from_request
    runtime_from_request
    addon_from_request
    names_from_request
    # The request is the worker's: take it out of its directory first (a
    # rename never follows a link), then read it only as a small regular
    # file.
    install -d -o root -g root -m 0755 "$STATUS_DIR"
    local req="$STATUS_DIR/.request.$$"
    mv -fT -- "$UPDATE_DIR/request.json" "$req" 2>/dev/null || exit 0
    if [ -L "$req" ] || [ ! -f "$req" ] || [ "$(stat -c %s "$req")" -gt 4096 ]; then rm -f -- "$req"; exit 0; fi
    want=$(jq -er '.version' < "$req" 2>/dev/null) || { rm -f -- "$req"; exit 0; }
    rm -f -- "$req"
    [[ "$want" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 0
  fi
  WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
  pubkey_pem
  fetch_signed "channels/$CHANNEL.json" "$WORK/channel.json" || die "cannot read the $CHANNEL channel"
  [ "$(json .channel "$WORK/channel.json")" = "$CHANNEL" ] || die "the $CHANNEL channel file names another channel"
  local latest cur
  latest=$(json .version "$WORK/channel.json"); cur=$(installed_version)
  [ -z "$want" ] && want=$latest
  STATUS_VERSION=$want
  if ! version_gt "$want" "$cur"; then
    log "ScalPanel $cur is installed; $want is not newer"
    [ $from_request = 1 ] && status "done" "ScalPanel $cur is up to date"
    exit 0
  fi
  if [ $yes = 0 ]; then
    printf 'Update ScalPanel %s to %s? [y/N] ' "$cur" "$want" > /dev/tty
    read -r ans < /dev/tty
    case "$ans" in y|Y|yes) ;; *) exit 1 ;; esac
  fi
  log "updating ScalPanel $cur to $want"
  download_release "$want"
  status installing "installing ScalPanel $RELEASE_VERSION" 82
  local prev
  prev=$(readlink -f "$OPT/current")
  cp "$ETC/release.env" "$LIB/state/release.env.previous"
  # A dump before every upgrade (ADR-0037 §2); the last three are kept.
  mkdir -p "$LIB/backups"
  compose exec -T postgres pg_dump -U "$NAMES" -Fc "$NAMES" > "$LIB/backups/pre-$RELEASE_VERSION-$(date -u +%Y%m%dT%H%M%SZ).dump" ||
    die "the pre-upgrade database dump failed"
  ls -1t "$LIB"/backups/pre-*.dump 2>/dev/null | tail -n +4 | xargs -r rm -f
  status installing "installing ScalPanel $RELEASE_VERSION" 86
  activate "$RELEASE_DIR"
  mail_upgrades "$RELEASE_DIR"
  mail_volume_cleanup
  mariadb_grants
  if ! compose pull --quiet; then
    # Nothing was restarted: the previous release's files come back.
    activate "$prev"
    die "the new images cannot be pulled from the local registry; $(basename "$prev") keeps running"
  fi
  status installing "restarting ScalPanel $RELEASE_VERSION" 92
  compose up -d --remove-orphans || true
  if ! wait_healthy 600 api worker webmail-api mail panel node; then
    log "ScalPanel $RELEASE_VERSION did not start; restoring $(basename "$prev")"
    cp "$LIB/state/release.env.previous" "$ETC/release.env"
    ln -sfn "$prev" "$OPT/current"
    # The schema may be newer than the previous binaries: additive
    # migrations only, so they may run on it (ADR-0037 §2).
    SCALPANEL_ALLOW_NEWER_SCHEMA=true compose up -d --remove-orphans || true
    die "ScalPanel $RELEASE_VERSION did not start; $(basename "$prev") was restored (database backup in $LIB/backups)"
  fi
  echo "$RELEASE_VERSION" > "$ETC/version"
  # Cleaning up never fails an update that is already running.
  prune_images || log "old images could not all be removed"
  # Old release directories: the current and the previous one stay.
  ls -1dt "$OPT"/releases/*/ 2>/dev/null | tail -n +3 | xargs -r rm -rf
  status "done" "ScalPanel $RELEASE_VERSION is installed" 100
  log "ScalPanel $RELEASE_VERSION is installed"
}

# ---------------------------------------------------------------- install
# The control plane's database password file, for the names in use.
write_pgpass() {
  printf 'postgres:5432:%s:%s:%s\n' "$NAMES" "$NAMES" "$(cat "$ETC/secrets/postgres")" > "$ETC/secrets/pgpass.new" &&
    chown root:$CP_UID "$ETC/secrets/pgpass.new" && chmod 0640 "$ETC/secrets/pgpass.new" &&
    mv -f "$ETC/secrets/pgpass.new" "$ETC/secrets/pgpass"
}

db_secrets() { # container secret...
  local c=$1; shift
  install -d -m 0700 "$ETC/db"
  install -d -m 0755 "$ETC/db/$c"
  local s
  for s in "$@"; do install -m 0644 "$ETC/secrets/$s" "$ETC/db/$c/$s"; done
}

gen_secret() { # name
  [ -s "$ETC/secrets/$1" ] || { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$ETC/secrets/$1"; }
}

cmd_install() {
  : "${SCALPANEL_HOSTNAME:?}" "${SCALPANEL_PUBLIC_IP:?}" "${SCALPANEL_ADMIN_EMAIL:?}"
  WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
  mkdir -p "$ETC/secrets" "$ETC/tls" "$ETC/release" "$UPDATE_DIR" "$LIB/registry" "$LIB/backups" "$LIB/state" "$SRV" "$OPT/releases"
  chmod 0755 "$ETC" "$LIB"
  chown root:$CP_UID "$ETC/secrets"; chmod 0750 "$ETC/secrets"
  chown $CP_UID:$CP_UID "$UPDATE_DIR"; chmod 0755 "$UPDATE_DIR"
  install -d -o root -g root -m 0755 "$STATUS_DIR"
  chmod 0711 "$SRV"
  NAMES=scalpanel

  # This server's settings.
  if [ ! -s "$ENV_FILE" ]; then
    cat > "$ENV_FILE" <<EOF
# ScalPanel server settings (ADR-0063). Edit, then: scalpanelctl compose up -d
SCALPANEL_HOSTNAME=$SCALPANEL_HOSTNAME
SCALPANEL_PUBLIC_IP=$SCALPANEL_PUBLIC_IP
SCALPANEL_ADMIN_EMAIL=$SCALPANEL_ADMIN_EMAIL
SCALPANEL_MAIL_HOSTNAME=${SCALPANEL_MAIL_HOSTNAME:-$SCALPANEL_HOSTNAME}
SCALPANEL_NAMESERVERS=${SCALPANEL_NAMESERVERS:-ns1.$SCALPANEL_HOSTNAME,ns2.$SCALPANEL_HOSTNAME}
SCALPANEL_UPDATE_URL=$UPDATE_URL
SCALPANEL_UPDATE_CHANNEL=$CHANNEL
SCALPANEL_NAMES=scalpanel
EOF
    # Installer tests only: a release site over plain HTTP.
    if [ "${SCALPANEL_ALLOW_HTTP:-0}" = 1 ]; then echo "SCALPANEL_ALLOW_HTTP=1" >> "$ENV_FILE"; fi
    chmod 0644 "$ENV_FILE"
  fi

  # Secrets, generated once.
  for s in postgres mariadb-root mariadb-provisioner pdns-api-key mail-db-admin mail-db-writer mail-db-reader \
           mail-db-webmail webmail-master ssh-gateway-token worker-internal-token backup-admin; do
    gen_secret "$s"
  done
  write_pgpass
  printf 'PDNS_AUTH_API_KEY=%s\n' "$(cat "$ETC/secrets/pdns-api-key")" > "$ETC/secrets/pdns.env"
  [ -s "$ETC/secrets/sshgw_host_ed25519" ] || ssh-keygen -q -t ed25519 -N '' -C scalpanel-sshgw -f "$ETC/secrets/sshgw_host_ed25519"
  chown root:$CP_UID "$ETC"/secrets/*; chmod 0640 "$ETC"/secrets/*
  # Each database container gets only its own passwords, readable by its
  # database user inside the container; $ETC/db itself is root only.
  db_secrets postgres postgres
  db_secrets mariadb mariadb-root mariadb-provisioner
  db_secrets mail-db mail-db-admin mail-db-writer mail-db-reader mail-db-webmail

  # The panels' fallback certificate (ADR-0063 §5); the hostname gets a
  # trusted one once it points here (ADR-0070).
  if [ ! -s "$ETC/tls/panel.crt" ]; then fallback_cert "$SCALPANEL_HOSTNAME" "$SCALPANEL_PUBLIC_IP"; fi

  pubkey_pem
  download_release "${SCALPANEL_VERSION:-}"
  local d=$RELEASE_DIR
  activate "$d"
  log "starting the registry and the databases"
  compose up -d registry postgres mariadb mail-db pdns
  wait_healthy 300 postgres mariadb mail-db || die "the databases did not start"
  compose pull --quiet || die "the images cannot be pulled from the local registry"
  # The schema includes every mail upgrade so far.
  : > "$LIB/state/mail-upgrades"
  for f in "$d"/mail/upgrade/*.sql; do
    if [ -e "$f" ]; then basename "$f" >> "$LIB/state/mail-upgrades"; fi
  done

  # The keyring (ADR-0006 §8), the database schema, the provider and its admin.
  if [ ! -s "$ETC/secrets/keyring" ]; then
    compose run --rm --no-deps -T migrate scalpanel-admin keyring-generate k1 > "$ETC/secrets/keyring.tmp"
    mv "$ETC/secrets/keyring.tmp" "$ETC/secrets/keyring"
  fi
  # The keyring is readable by the services' user only (ADR-0006 §8).
  chown $CP_UID:$CP_UID "$ETC/secrets/keyring"; chmod 0600 "$ETC/secrets/keyring"
  if [ ! -s "$ETC/secrets/backup-admin.htpasswd" ]; then
    compose run --rm --no-deps -T migrate scalpanel-htpasswd admin < "$ETC/secrets/backup-admin" > "$ETC/secrets/backup-admin.htpasswd"
    chown root:$CP_UID "$ETC/secrets/backup-admin.htpasswd"; chmod 0640 "$ETC/secrets/backup-admin.htpasswd"
  fi
  compose run --rm -T migrate scalpanel-migrate up
  # Each first-time step checks the database, so an interrupted
  # installation can simply run again. The admin password is kept (root
  # only) until it has been shown.
  local pw=""
  if [ "$(sql "SELECT count(*) FROM tenants WHERE kind = 'provider'")" = 0 ]; then
    # Always 20 characters: 30 random bytes leave far more than 20 after
    # dropping / + =.
    head -c 30 /dev/urandom | base64 | tr -d '/+=' | cut -c1-20 > "$LIB/state/admin-password"
    chmod 0600 "$LIB/state/admin-password"
    compose run --rm -T -e SCALPANEL_BOOTSTRAP_EMAIL="$SCALPANEL_ADMIN_EMAIL" migrate scalpanel-admin bootstrap < "$LIB/state/admin-password"
  fi
  [ -s "$LIB/state/admin-password" ] && pw=$(cat "$LIB/state/admin-password")
  if [ "$(sql "SELECT count(*) FROM database_servers WHERE name = 'main'")" = 0 ]; then
    compose run --rm -T migrate scalpanel-admin dbserver-add main mariadb 3306 3306 scalpanel_prov < "$ETC/secrets/mariadb-provisioner"
  fi
  if [ ! -s "$ETC/secrets/node.bundle" ]; then
    if [ "$(sql "SELECT count(*) FROM nodes WHERE name = 'node-1'")" != 0 ]; then
      die "node-1 is registered but its enrollment bundle is missing; remove the node in the database or restore $ETC/secrets/node.bundle"
    fi
    # The bundle is the line starting with spe1. (logs share stdout).
    compose run --rm -T migrate scalpanel-admin node-create node-1 web | grep '^spe1\.' > "$ETC/secrets/node.bundle.tmp" ||
      die "the node could not be registered"
    mv "$ETC/secrets/node.bundle.tmp" "$ETC/secrets/node.bundle"
    chown root:$CP_UID "$ETC/secrets/node.bundle"; chmod 0640 "$ETC/secrets/node.bundle"
  fi
  # The worker (UID 10001) writes the backup store's user file.
  compose run --rm --no-deps -T --user 0 --entrypoint chown worker "$CP_UID:$CP_UID" /run/backup-users
  log "starting ScalPanel"
  compose up -d --remove-orphans || die "ScalPanel did not start; see: scalpanelctl compose ps"
  wait_healthy 900 api worker webmail-api mail panel node || die "ScalPanel did not become healthy; see: scalpanelctl status"
  echo "$STATUS_VERSION" > "$ETC/version"
  systemctl enable --now scalpanel-update.path >/dev/null 2>&1 || true
  status "done" "ScalPanel $STATUS_VERSION is installed"
  cat <<EOF

  ScalPanel $STATUS_VERSION is installed.

    Admin panel     https://$SCALPANEL_HOSTNAME:2087   (or https://$SCALPANEL_PUBLIC_IP:2087)
    Customer panel  https://$SCALPANEL_HOSTNAME:2083
    Webmail         https://$SCALPANEL_HOSTNAME:2096
EOF
  if [ -n "$pw" ]; then
    cat <<EOF

    Username        admin
    Password        $pw        (change it after signing in)
EOF
    rm -f "$LIB/state/admin-password"
  fi
  cat <<EOF

  The panels get a trusted certificate automatically once $SCALPANEL_HOSTNAME
  points at this server; until then they use a self-signed one.
  To change the hostname later: scalpanelctl set-hostname <name>

  DNS: point $SCALPANEL_HOSTNAME (A) to $SCALPANEL_PUBLIC_IP; for hosted DNS,
  create glue records for the nameservers in $ENV_FILE.
  Updates appear in the admin panel (Settings > Updates).
EOF
}

# ---------------------------------------------------------------- hostname
# The installer's fallback certificate for the panels (ADR-0063 §5): any
# name and the IP; a hostname that points at this server gets a trusted
# certificate from the worker (ADR-0070).
fallback_cert() { # hostname ip
  openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 825 \
    -subj "/CN=$1" -addext "subjectAltName=DNS:$1,IP:$2" \
    -keyout "$ETC/tls/panel.key.new" -out "$ETC/tls/panel.crt.new" 2>/dev/null || die "cannot create the panel certificate"
  chmod 0644 "$ETC/tls/panel.crt.new"; chmod 0600 "$ETC/tls/panel.key.new"
  mv "$ETC/tls/panel.key.new" "$ETC/tls/panel.key"; mv "$ETC/tls/panel.crt.new" "$ETC/tls/panel.crt"
}

cmd_set_hostname() {
  local new old ip
  new=$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]'); new=${new%.}
  if ! [[ "$new" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] || [ ${#new} -gt 253 ]; then
    die "usage: scalpanelctl set-hostname <panel.example.com>"
  fi
  [ -s "$ENV_FILE" ] || die "ScalPanel is not installed"
  old=$(setting SCALPANEL_HOSTNAME "")
  ip=$(setting SCALPANEL_PUBLIC_IP "")
  if [ "$new" = "$old" ]; then
    log "the hostname is already $new"
    return 0
  fi
  sed -i "s/^SCALPANEL_HOSTNAME=.*/SCALPANEL_HOSTNAME=$new/" "$ENV_FILE"
  # The mail hostname followed the panel's unless it was set on its own.
  if grep -qxF "SCALPANEL_MAIL_HOSTNAME=$old" "$ENV_FILE"; then
    sed -i "s/^SCALPANEL_MAIL_HOSTNAME=.*/SCALPANEL_MAIL_HOSTNAME=$new/" "$ENV_FILE"
  fi
  fallback_cert "$new" "$ip"
  compose up -d --remove-orphans || die "the services did not restart"
  cat <<EOF

  The panel hostname is now $new.
  Point $new (A) to ${ip:-this server}; a trusted certificate for :2083,
  :2087 and :2096 is then issued automatically within a few minutes.
EOF
}

# The host's global IPv4 addresses, one per line.
host_ipv4s() {
  ip -4 -o addr show scope global 2>/dev/null | awk '{ sub(/\/.*/, "", $4); print $4 }'
}

# The server's public IPv4 address changed (new provider address, moved VM):
# the services bind DNS and FTP to the new one, the server and the provider's
# web address in the database follow, and hosted A records move with them.
cmd_set_ip() {
  local new old hn force=""
  new=${1:-}; shift || true
  old=$(setting SCALPANEL_PUBLIC_IP "")
  while [ $# -gt 0 ]; do
    case "$1" in
      --force) force=1 ;;
      --from) old=${2:-}; shift ;; # the address the panel still shows, when the file was edited by hand
      *) die "usage: scalpanelctl set-ip <new IPv4 address> [--from <old address>] [--force]" ;;
    esac
    shift
  done
  local re='^[0-9]{1,3}(\.[0-9]{1,3}){3}$'
  [[ "$new" =~ $re ]] || die "usage: scalpanelctl set-ip <new IPv4 address> [--from <old address>] [--force]"
  [ -z "$old" ] || [[ "$old" =~ $re ]] || die "--from takes the old IPv4 address"
  [ -s "$ENV_FILE" ] || die "ScalPanel is not installed"
  hn=$(setting SCALPANEL_HOSTNAME "")
  if [ -z "$force" ] && ! host_ipv4s | grep -qxF "$new"; then
    die "$new is not an address of this server ($(host_ipv4s | paste -sd' ')); add it first, or pass --force behind NAT"
  fi
  [ "$new" != "$old" ] || die "the address is already $new; if the panel still shows the old one: scalpanelctl set-ip $new --from <old address>"
  sed -i "s/^SCALPANEL_PUBLIC_IP=.*/SCALPANEL_PUBLIC_IP=$new/" "$ENV_FILE"
  compose up -d postgres || die "the database did not start"
  [ -z "$old" ] || admin change-address "$old" "$new" || die "the database could not be updated; run scalpanelctl set-ip $new --from $old again"
  if [ -n "$hn" ]; then fallback_cert "$hn" "$new"; fi
  if [ -s "$ETC/compose.link.yaml" ]; then link_write; fi
  compose up -d --remove-orphans || die "the services did not restart"
  cat <<EOF

  The server's address is now $new${old:+ (was $old)}.
  - DNS records of hosted zones that pointed to $old now point to $new.
  - Point $hn (A) to $new where its DNS is hosted elsewhere, and update the
    glue records of your nameservers at the registrar if they used $old.
  - Addresses you added under IP addresses stay; remove $old there if it is listed.
EOF
  if [ -s "$LINK_DIR/peers" ]; then
    echo "  - Linked nodes: on each, set Endpoint = $new:$LINK_PORT in $LINK_CONF and run"
    echo "    systemctl restart wg-quick@sp-link."
  fi
}

# ---------------------------------------------------------------- restart
cmd_restart() {
  [ $# -ge 1 ] || die "usage: scalpanelctl restart <service>... ($(echo api worker panel node postgres mariadb pdns mail mail-db webmail-api sshgw backup-store))"
  local s
  for s in "$@"; do service_ok "$s" || die "unknown service: $s"; done
  restart_services "$@"
}

# A new enrollment bundle for node-1 (Servers → Nodes → New enrollment
# bundle), read from standard input so it never shows in the process list.
# The agent uses it when its certificate expired; it keeps its ID and websites.
cmd_node_bundle() {
  local b
  IFS= read -r b || true
  case "$b" in spe1.*) ;; *) die "paste the bundle (it starts with spe1.) on standard input" ;; esac
  [ ${#b} -le 16384 ] || die "the bundle is too long"
  umask 077
  printf '%s\n' "$b" > "$ETC/secrets/node.bundle.tmp"
  chown root:$CP_UID "$ETC/secrets/node.bundle.tmp"; chmod 0640 "$ETC/secrets/node.bundle.tmp"
  mv "$ETC/secrets/node.bundle.tmp" "$ETC/secrets/node.bundle"
  log "bundle saved; the node re-enrolls within a minute if its certificate expired"
}

# The edge reads its configuration again; websites keep running.
cmd_reload_edge() {
  compose exec -T node sh -c 'kill -HUP "$(cat /run/scalpanel-edge.pid)"'
  log "edge nginx reloaded"
}

# ---------------------------------------------------------------- the private link
# Nodes on other servers reach this server over WireGuard (ADR-0232):
# sp-link is 10.99.0.1/24; each node gets the next address. Only the
# services published in compose.link.yaml answer on it, and only for nodes.
LINK_DIR=$ETC/link
LINK_CONF=/etc/wireguard/sp-link.conf
LINK_PORT=51820
link_name_ok() { [[ "$1" =~ ^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }

link_nft() {
  cat <<'EOF'
# Generated by scalpanelctl (ADR-0232). From the link, only connections to
# ports Docker publishes on 10.99.0.1 pass; to the link, only the SSH
# gateway's and the web terminal's connections to the nodes' :9444 and
# webmail's to mail servers' IMAP and submission (ADR-0233).
# Loaded again as a whole: the empty table and its deletion make it replace
# the running one.
table inet sp_link
delete table inet sp_link
table inet sp_link {
  chain forward_link {
    type filter hook forward priority -10; policy accept;
    iifname "sp-link" ct state established,related accept
    iifname "sp-link" ct status dnat accept
    iifname "sp-link" drop
    oifname "sp-link" ct state established,related accept
    oifname "sp-link" ct state new tcp dport { 9444, 993, 587 } accept
    oifname "sp-link" drop
  }
  chain input_link {
    type filter hook input priority -10; policy accept;
    iifname "sp-link" ct state established,related accept
    iifname "sp-link" icmp type echo-request accept
    iifname "sp-link" drop
  }
}
EOF
}

# compose.link.yaml and sp-link.conf from the peers file.
link_write() {
  local peers="$LINK_DIR/peers" hosts="" edges mailsrv="" name addr key ip role
  # The nodes' public addresses are edges too: certificates over HTTP-01
  # and uptime checks of their websites, a mail server's challenges.
  edges=$(setting SCALPANEL_PUBLIC_IP "")
  while read -r name addr key ip role _; do
    [ -n "$name" ] || continue
    hosts+="      - \"$name:$addr\""$'\n'
    [ -n "$ip" ] && edges+=",$ip"
    # Webmail reaches a mail server over the link, by its pinned certificate.
    [ "$role" = mail ] && mailsrv+="${mailsrv:+,}$name=$addr:993:587:scalpanel-mail.internal"
  done < "$peers"
  local reg_image
  reg_image=$(compose config --images 2>/dev/null | grep -m1 '^registry:') || die "the registry image is not known"
  {
    echo "# Generated by scalpanelctl link (ADR-0232); do not edit."
    echo "services:"
    echo "  worker:"
    echo "    ports: [\"10.99.0.1:9443:9443\"]"
    for s in worker api sshgw; do
      [ "$s" = worker ] || echo "  $s:"
      [ "$s" = sshgw ] || printf '    environment:\n      SCALPANEL_EDGE_ADDRESSES: "%s"\n' "$edges"
      [ -n "$hosts" ] && printf '    extra_hosts:\n%s' "$hosts"
    done
    echo "  mariadb:"
    echo "    ports: [\"10.99.0.1:3306:3306\"]"
    echo "  mail:"
    # The host's 465 is the public submission port; nodes use 5465.
    echo "    ports: [\"10.99.0.1:5465:465\"]"
    echo "    environment:"
    echo "      MAIL_TRUSTED_NETS: 10.231.0.0/24,10.99.0.0/24"
    if [ -n "$mailsrv" ]; then
      # Mail servers on other machines read the mail directory (ADR-0233).
      echo "  mail-db:"
      echo "    ports: [\"10.99.0.1:5432:5432\"]"
      echo "  webmail-api:"
      echo "    environment:"
      echo "      SCALPANEL_WEBMAIL_SERVERS: \"$mailsrv\""
    fi
    echo "  backup-store:"
    echo "    ports: [\"10.99.0.1:8000:8000\"]"
    echo "  registry-link:"
    echo "    image: $reg_image"
    echo "    restart: unless-stopped"
    echo "    read_only: true"
    echo "    ports: [\"10.99.0.1:5000:5000\"]"
    echo "    volumes:"
    echo "      - $LIB/registry:/var/lib/registry:ro"
    echo "      - $LINK_DIR/registry.yml:/etc/distribution/config.yml:ro"
    echo "    tmpfs: [/tmp]"
  } > "$ETC/compose.link.yaml.tmp"
  # The registry for nodes serves the same images and refuses every write.
  printf 'version: 0.1
storage:
  filesystem:
    rootdirectory: /var/lib/registry
  maintenance:
    readonly:
      enabled: true
    uploadpurging:
      enabled: false
http:
  addr: :5000
' > "$LINK_DIR/registry.yml"
  chmod 0644 "$LINK_DIR/registry.yml"
  mv "$ETC/compose.link.yaml.tmp" "$ETC/compose.link.yaml"
  link_nft > "$LINK_DIR/link.nft"
  (
    umask 077
    {
      echo "# Generated by scalpanelctl link (ADR-0232); do not edit."
      echo "[Interface]"
      echo "Address = 10.99.0.1/24"
      echo "ListenPort = $LINK_PORT"
      echo "PrivateKey = $(cat "$LINK_DIR/key")"
      echo "PostUp = nft -f $LINK_DIR/link.nft"
      echo "PostDown = nft delete table inet sp_link"
      while read -r name addr key _; do
        [ -n "$name" ] && printf '\n# %s\n[Peer]\nPublicKey = %s\nAllowedIPs = %s/32\n' "$name" "$key" "$addr"
      done < "$peers"
    } > "$LINK_CONF.tmp"
    mv "$LINK_CONF.tmp" "$LINK_CONF"
  )
}

link_apply() { # services to recreate
  if systemctl is-active -q wg-quick@sp-link; then
    wg syncconf sp-link <(wg-quick strip sp-link) || die "the link could not be updated"
    nft -f "$LINK_DIR/link.nft" || die "the link's firewall rules could not be loaded"
  else
    systemctl enable -q --now wg-quick@sp-link || die "the link does not start (see: journalctl -u wg-quick@sp-link)"
  fi
  compose up -d --no-deps "$@" >/dev/null || die "the services did not start"
}

link_init() {
  [ -s "$LINK_DIR/key" ] && [ -s "$ETC/compose.link.yaml" ] && { log "the link is set up already"; return 0; }
  if ! command -v wg >/dev/null || ! command -v nft >/dev/null; then
    log "installing WireGuard"
    if command -v dnf >/dev/null; then # the RHEL family (ADR-0234)
      dnf install -y -q wireguard-tools nftables >/dev/null || die "wireguard-tools could not be installed"
    else
      DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y -qq wireguard-tools nftables >/dev/null || die "wireguard-tools could not be installed"
    fi
  fi
  install -d -m 0700 "$LINK_DIR"
  [ -e "$LINK_DIR/peers" ] || : > "$LINK_DIR/peers"
  [ -s "$LINK_DIR/key" ] || (umask 077; wg genkey > "$LINK_DIR/key")
  # Docker starts after the link: its ports on 10.99.0.1 bind at boot.
  install -d /etc/systemd/system/docker.service.d
  printf '[Unit]\nAfter=wg-quick@sp-link.service\nWants=wg-quick@sp-link.service\n' > /etc/systemd/system/docker.service.d/scalpanel-link.conf
  systemctl daemon-reload
  link_write
  log "starting the link; the mail server, MariaDB and the control plane restart once"
  link_apply worker api sshgw mariadb mail backup-store registry-link
  log "the link listens on UDP $LINK_PORT: open it in any firewall in front of this server"
}

link_ip_ok() { [[ "$1" =~ ^((25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])$ ]]; }

link_add() { # name public-key public-ip [--mail hostname]
  local name=${1:-} key=${2:-} pub=${3:-} role=web host=""
  link_name_ok "$name" || die "usage: scalpanelctl link add <node name> <the node's public key> <its public IPv4> [--mail <hostname>] (the name as in Servers -> Nodes)"
  [[ "$key" =~ ^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw480]=$ ]] || die "that is not a WireGuard public key"
  link_ip_ok "$pub" || die "give the node's public IPv4 address after its key"
  case "${4:-}" in
    "") ;;
    --mail)
      role=mail host=${5:-}
      [[ "$host" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]] || die "--mail needs the mail server's hostname"
      ;;
    *) die "usage: scalpanelctl link add <node name> <key> <ip> [--mail <hostname>]" ;;
  esac
  [ -s "$LINK_DIR/key" ] || die "set up the link first: scalpanelctl link init"
  awk -v n="$name" -v k="$key" '$1 == n || $3 == k {f = 1} END {exit !f}' "$LINK_DIR/peers" && die "$name or its key is linked already"
  local ip; ip=$(setting SCALPANEL_PUBLIC_IP "")
  [ -n "$ip" ] || die "SCALPANEL_PUBLIC_IP is not set"
  local image
  if [ "$role" = mail ]; then
    image=$(grep '^SCALPANEL_IMAGE_MAIL=' "$ETC/release.env" | grep -o 'scalpanel/mail@sha256:[0-9a-f]\{64\}$' || true)
  else
    image=$(grep '^SCALPANEL_IMAGE_NODE=' "$ETC/release.env" | grep -o 'scalpanel/node@sha256:[0-9a-f]\{64\}$' || true)
  fi
  [ -n "$image" ] || die "the $role image of this release is not known"
  local i addr=""
  for i in $(seq 2 254); do
    awk -v a="10.99.0.$i" '$2 == a {f = 1} END {exit !f}' "$LINK_DIR/peers" || { addr=10.99.0.$i; break; }
  done
  [ -n "$addr" ] || die "the link has no free address"
  local secrets=""
  if [ "$role" = mail ]; then
    # Its own directory login (ADR-0233), shown once below.
    local pw; pw=$(head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n')
    link_mail_role "$name" "$pw" || die "the mail directory login could not be made"
    secrets=$(printf '{"db":"%s","user":"mailsrv_%s","password":"%s","webmail":"%s"}' "${NAMES}_mail" "$name" "$pw" "$(cat "$ETC/secrets/webmail-master")" | base64 -w0)
    printf '%s %s %s %s mail %s\n' "$name" "$addr" "$key" "$pub" "$host" >> "$LINK_DIR/peers"
  else
    printf '%s %s %s %s\n' "$name" "$addr" "$key" "$pub" >> "$LINK_DIR/peers"
  fi
  link_write
  if [ "$role" = mail ]; then link_apply worker api sshgw mail-db webmail-api; else link_apply worker api sshgw; fi
  local code
  code=$(printf '{"endpoint":"%s:%s","key":"%s","address":"%s","image":"%s","role":"%s"}' "$ip" "$LINK_PORT" "$(wg pubkey < "$LINK_DIR/key")" "$addr" "$image" "$role" | base64 -w0 | tr '+/' '-_' | tr -d '=')
  log "$name is linked as $addr; on $name, run install-node.sh again with:"
  printf -- '--link spl1.%s\n' "$code"
  if [ -n "$secrets" ]; then
    log "and these secrets in its environment (shown only now; keep them out of logs):"
    printf "SCALPANEL_MAIL_SECRETS='%s'\n" "$secrets"
    log "then add the mail server under Mail servers: name $name, hostname $host"
  fi
}

# A mail server's own login to the mail directory (ADR-0233): a member of
# the servers' reader role that reads and writes only its own certificates.
# Made again (new password) if it exists; without a password, dropped.
link_mail_role() { # name [password]
  {
    printf '\\set r mailsrv_%s\n\\set reader %s_mail_reader\n\\set s %s\n' "$1" "$NAMES" "$1"
    [ -n "${2:-}" ] && printf '\\set p %s\n' "$2"
    cat <<'SQL'
\set ON_ERROR_STOP 1
SELECT format('DROP OWNED BY %I', :'r') FROM pg_roles WHERE rolname = :'r' \gexec
SELECT format('DROP ROLE %I', :'r') FROM pg_roles WHERE rolname = :'r' \gexec
DELETE FROM server_tls WHERE server = :'s';
DELETE FROM server_certificates WHERE server = :'s';
SQL
    [ -n "${2:-}" ] && cat <<'SQL'
SELECT format('CREATE ROLE %I LOGIN PASSWORD %L IN ROLE %I', :'r', :'p', :'reader') \gexec
SELECT format('GRANT SELECT ON server_certificates TO %I', :'r') \gexec
SELECT format('GRANT SELECT, INSERT, UPDATE ON server_tls TO %I', :'r') \gexec
SQL
    true
  } | compose exec -T mail-db psql -qAt -U mailadmin -d "${NAMES}_mail" >/dev/null
}

link_remove() {
  local name=${1:-} role
  link_name_ok "$name" || die "usage: scalpanelctl link remove <node name>"
  awk -v n="$name" '$1 == n {f = 1} END {exit !f}' "$LINK_DIR/peers" 2>/dev/null || die "$name is not linked"
  role=$(awk -v n="$name" '$1 == n {print $5}' "$LINK_DIR/peers")
  awk -v n="$name" '$1 != n' "$LINK_DIR/peers" > "$LINK_DIR/peers.tmp" && mv "$LINK_DIR/peers.tmp" "$LINK_DIR/peers"
  link_write
  if [ "$role" = mail ]; then
    link_mail_role "$name" || log "warning: the mail directory login mailsrv_$name could not be removed"
    link_apply worker api sshgw mail-db webmail-api
  else
    link_apply worker api sshgw
  fi
  log "$name is no longer linked"
}

# A node's public address (nodes linked by 0.1.40 have none).
link_set_ip() {
  local name=${1:-} pub=${2:-}
  link_name_ok "$name" && link_ip_ok "$pub" || die "usage: scalpanelctl link set-ip <node name> <its public IPv4>"
  awk -v n="$name" '$1 == n {f = 1} END {exit !f}' "$LINK_DIR/peers" 2>/dev/null || die "$name is not linked"
  awk -v n="$name" -v p="$pub" '$1 == n {$4 = p} {print}' "$LINK_DIR/peers" > "$LINK_DIR/peers.tmp" && mv "$LINK_DIR/peers.tmp" "$LINK_DIR/peers"
  link_write
  link_apply worker api
  log "$name's public address is $pub"
}

cmd_link() {
  local sub=${1:-list}; shift || true
  case "$sub" in
    init) link_init ;;
    add) link_add "$@" ;;
    remove) link_remove "$@" ;;
    set-ip) link_set_ip "$@" ;;
    list)
      [ -s "$LINK_DIR/key" ] || { echo "no link (set it up with: scalpanelctl link init)"; return 0; }
      echo "this server: 10.99.0.1, UDP $LINK_PORT, key $(wg pubkey < "$LINK_DIR/key")"
      while read -r name addr _ ip role host; do
        [ -n "$name" ] && printf '%-24s %-12s %-5s %s %s\n' "$name" "$addr" "${role:-web}" "${ip:-(no public address: link set-ip)}" "${host:-}"
      done < "$LINK_DIR/peers"
      command -v wg >/dev/null && wg show sp-link latest-handshakes 2>/dev/null | sed 's/^/handshake: /' || true ;;
    *) die "usage: scalpanelctl link init | add <node> <key> <ip> [--mail <hostname>] | set-ip <node> <ip> | remove <node> | list" ;;
  esac
}

# ---------------------------------------------------------------- the move
# A server installed as vPanel moves to the ScalPanel names (ADR-0174) once a
# ScalPanel release is installed and running: /etc, /var/lib, /opt and /srv
# vpanel become scalpanel, each old name a link to the new one; a directory
# that is a mount point of its own stays and the new name links to it. The
# compose project becomes scalpanel and keeps the volumes it has. Websites
# restart once. If the services do not come back, everything goes back.
move_dir() { # old new moves-file
  [ -L "$1" ] || [ ! -e "$1" ] && return 0
  if [ -e "$2" ] || [ -L "$2" ]; then
    rmdir "$2" 2>/dev/null || { log "$2 exists already: move it away, then run scalpanelctl move-layout"; return 1; }
  fi
  if mountpoint -q "$1"; then
    ln -s "$1" "$2" || return 1
    printf '%s %s\n' "$1" "$2" >> "$3"
    return 0
  fi
  mv -T "$1" "$2" || return 1
  printf '%s %s\n' "$1" "$2" >> "$3"
  ln -s "$2" "$1"
}

move_back() { # moves-file
  local o n
  tac "$1" | while read -r o n; do
    if [ -L "$o" ] && [ "$(readlink "$o")" = "$n" ] && [ -d "$n" ] && [ ! -L "$n" ]; then
      rm -f "$o"; mv -T "$n" "$o"
    elif [ ! -e "$o" ] && [ ! -L "$o" ] && [ -d "$n" ] && [ ! -L "$n" ]; then
      mv -T "$n" "$o"
    elif [ -L "$n" ] && [ "$(readlink "$n")" = "$o" ]; then
      rm -f "$n"
    fi
  done
}

# Runs the move when the server is ready for it (a ScalPanel release is
# current and fully installed), or finishes an interrupted one; else the
# server keeps the old names for now. Holds both updaters' locks.
layout_move_when_ready() { # [force]
  exec 8>/run/vpanel-update.lock
  flock -w 7000 8 || die "an update is running; try again later"
  exec 7>/run/scalpanel-update.lock
  flock -w 7000 7 || die "an update is running; try again later"
  local cur ver
  if [ -e "$MOVING" ]; then
    ver=$(head -c 40 "$MOVING")
    [[ "$ver" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "$MOVING is not a version; remove it after checking the server"
    log "finishing the interrupted move to the ScalPanel names"
    layout_move "$ver"
    exec 7>&- 8>&-; return 0
  fi
  if ! old_layout; then exec 7>&- 8>&-; set_layout; return 0; fi
  cur=$(readlink -f "$OLD_OPT/current" 2>/dev/null || true)
  ver=$(cat "$OLD_ETC/version" 2>/dev/null || true)
  if [ -z "$cur" ] || [ ! -f "$cur/bin/scalpanelctl" ] || [ "$(basename "$cur")" != "$ver" ]; then
    log "the server keeps its vPanel names until a ScalPanel release is installed"
    exec 7>&- 8>&-; return 1
  fi
  if [ -e "$OLD_LIB/state/layout-move-failed" ] && [ "${1:-}" != force ]; then
    log "the move to the ScalPanel names failed before; retry with: scalpanelctl move-layout"
    exec 7>&- 8>&-; return 1
  fi
  rm -f "$OLD_LIB/state/layout-move-failed"
  layout_move "$ver"
  exec 7>&- 8>&-
}

# Every step can run again: an interrupted move ($MOVING, its moves in
# $MOVING.moves) is finished by the next run, or undone if it fails.
layout_move() { # version
  local ver=$1 tmp moves="$MOVING.moves" v key ids ok=1
  trap '' INT HUP
  tmp=$(mktemp -d)
  STATUS_VERSION=$ver
  log "moving the server to the ScalPanel names (ADR-0174); websites restart once"
  status installing "renaming the server's directories and services to ScalPanel; websites restart once"
  # The volumes keep the names they were created with; without the
  # databases' volumes nothing is moved (the panel would start empty).
  {
    echo "# Written by scalpanelctl when this server moved to the ScalPanel names"
    echo "# (ADR-0174): its Docker volumes keep the names they were created with."
    echo "volumes:"
    for v in $(docker volume ls -q --filter label=com.docker.compose.project=vpanel); do
      key=$(docker volume inspect -f '{{index .Labels "com.docker.compose.volume"}}' "$v" 2>/dev/null) || continue
      [[ "$key" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || continue
      printf '  %s:\n    name: %s\n    external: true\n' "$key" "$v"
    done
  } > "$tmp/compose.volumes.yaml"
  for v in pg-data mariadb-data mail-db-data; do
    if ! grep -qxF "    name: vpanel_$v" "$tmp/compose.volumes.yaml"; then
      rm -rf "$tmp"
      [ -s "$moves" ] || rm -f "$MOVING" "$moves"
      die "the volume vpanel_$v was not found; nothing more was moved (see scalpanelctl move-layout)"
    fi
  done
  printf '%s\n' "$ver" > "$MOVING"
  touch "$moves"
  # The vPanel project's containers stop (by label: no compose file needed).
  ids=$(docker ps -aq --filter label=com.docker.compose.project=vpanel)
  if [ -n "$ids" ]; then
    # shellcheck disable=SC2086 # container IDs
    if ! { docker stop -t 120 $ids >/dev/null && docker rm $ids >/dev/null; }; then
      if [ ! -s "$moves" ]; then
        compose up -d --remove-orphans || true
        rm -f "$MOVING" "$moves"
      fi
      rm -rf "$tmp"
      mkdir -p "$LIB/state" && touch "$LIB/state/layout-move-failed"
      die "the vPanel services could not be stopped (retry: scalpanelctl move-layout)"
    fi
  fi
  docker network ls -q --filter label=com.docker.compose.project=vpanel | xargs -r docker network rm >/dev/null 2>&1 || true
  for v in OPT LIB SRV ETC; do
    local o="OLD_$v" n="NEW_$v"
    move_dir "${!o}" "${!n}" "$moves" || { ok=0; break; }
  done
  if [ $ok = 1 ]; then
    set_layout
    if [ -f "$NEW_ETC/vpanel.env" ]; then
      { sed -e 's/^# vPanel server settings (ADR-0063). Edit, then: vpanelctl compose up -d$/# ScalPanel server settings (ADR-0063). Edit, then: scalpanelctl compose up -d/' \
          "$NEW_ETC/vpanel.env" > "$NEW_ETC/scalpanel.env.new" &&
        chmod 0644 "$NEW_ETC/scalpanel.env.new" &&
        mv -f "$NEW_ETC/scalpanel.env.new" "$NEW_ETC/scalpanel.env" &&
        rm -f "$NEW_ETC/vpanel.env"; } || ok=0
    fi
  fi
  if [ $ok = 1 ]; then
    install -m 0644 "$tmp/compose.volumes.yaml" "$NEW_ETC/compose.volumes.yaml"
    ln -sfn "$NEW_OPT/releases/$ver" "$NEW_OPT/current.new" && mv -T "$NEW_OPT/current.new" "$NEW_OPT/current"
    write_release_env "$NEW_OPT/current"
    install_ctl "$NEW_OPT/current"
    install_units "$NEW_OPT/current"
    systemctl enable --now scalpanel-update.path >/dev/null 2>&1 || true
    scripts_link
    if compose up -d --remove-orphans && wait_healthy 600 api worker webmail-api mail panel node; then
      rm -rf "$tmp"
      rm -f "$MOVING" "$moves"
      trap - INT HUP
      status "done" "ScalPanel $ver: moved to $NEW_ETC, $NEW_LIB, $NEW_OPT and $NEW_SRV"
      log "moved: $NEW_ETC, $NEW_LIB, $NEW_OPT, $NEW_SRV (the old names link to them); scalpanelctl, scalpanel-update.path"
      return 0
    fi
    log "the services did not start with the ScalPanel names; going back"
    compose down --remove-orphans || true
  fi
  # Back to the vPanel names.
  if [ -f "$NEW_ETC/scalpanel.env" ] && [ ! -e "$NEW_ETC/vpanel.env" ]; then mv "$NEW_ETC/scalpanel.env" "$NEW_ETC/vpanel.env"; fi
  rm -f "$NEW_ETC/compose.volumes.yaml" "$NEW_ETC/scalpanel.env.new"
  move_back "$moves"
  set_layout
  ln -sfn "$OPT/releases/$ver" "$OPT/current.new" && mv -T "$OPT/current.new" "$OPT/current"
  install_units "$OPT/current"
  scripts_link
  compose up -d --remove-orphans || true
  mkdir -p "$LIB/state" && touch "$LIB/state/layout-move-failed"
  rm -rf "$tmp"
  rm -f "$MOVING" "$moves"
  die "the move to the ScalPanel names failed and was undone; the server runs as before (retry: scalpanelctl move-layout)"
}

# ---------------------------------------------------------------- names
# The databases, their roles and the Docker volumes take the ScalPanel names
# (ADR-0201): the control plane's database and role vpanel, the mail
# directory vpanel_mail and its roles, MariaDB's vpanel_prov, and the volumes
# a server installed as vPanel kept (compose.volumes.yaml). Every step checks
# what is done, so an interrupted move ($ETC/.names-moving) is finished by
# the next run; a failed one is undone. Websites keep running on the node;
# the panels and mail stop for the move.

pg_has_role() { # service superuser role
  [ "$(compose exec -T "$1" psql -U "$2" -d postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname = '$3'" 2>/dev/null | tr -d '\r')" = 1 ]
}

pg_has_db() { # service superuser database
  [ "$(compose exec -T "$1" psql -U "$2" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname = '$3'" 2>/dev/null | tr -d '\r')" = 1 ]
}

# Renames the databases and roles from one set of names to the other.
rename_dbs() { # from to
  local from=$1 to=$2 r
  # The control plane's superuser is the role being renamed: a temporary
  # superuser does it (the socket trusts local connections).
  if pg_has_role postgres "$from" "$from" 2>/dev/null || pg_has_role postgres "$to" "$from"; then
    local su=$from
    pg_has_role postgres "$from" "$from" 2>/dev/null || su=$to
    compose exec -T postgres psql -v ON_ERROR_STOP=1 -U "$su" -d postgres -qc "DROP ROLE IF EXISTS scalpanel_move" -c "CREATE ROLE scalpanel_move SUPERUSER LOGIN" >/dev/null || return 1
    compose exec -T postgres psql -v ON_ERROR_STOP=1 -U scalpanel_move -d postgres -q \
      -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND (usename = '$from' OR datname = '$from')" \
      -c "ALTER ROLE $from RENAME TO $to" >/dev/null || return 1
  fi
  if pg_has_db postgres "$to" "$from"; then
    compose exec -T postgres psql -v ON_ERROR_STOP=1 -U "$to" -d postgres -q \
      -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$from'" \
      -c "ALTER DATABASE $from RENAME TO $to" >/dev/null || return 1
  fi
  # A renamed role keeps a SCRAM password; set again all the same. psql
  # substitutes :'pw' only in SQL read from its input, not in -c.
  printf "ALTER ROLE %s PASSWORD :'pw';\nDROP ROLE IF EXISTS scalpanel_move;\n" "$to" |
    compose exec -T postgres psql -v ON_ERROR_STOP=1 -U "$to" -d postgres -q -v pw="$(cat "$ETC/secrets/postgres")" >/dev/null || return 1
  # The mail directory: its superuser is mailadmin.
  if pg_has_db mail-db mailadmin "${from}_mail"; then
    compose exec -T mail-db psql -v ON_ERROR_STOP=1 -U mailadmin -d postgres -q \
      -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${from}_mail'" \
      -c "ALTER DATABASE ${from}_mail RENAME TO ${to}_mail" >/dev/null || return 1
  fi
  for r in writer reader webmail; do
    if pg_has_role mail-db mailadmin "${from}_mail_$r"; then
      compose exec -T mail-db psql -v ON_ERROR_STOP=1 -U mailadmin -d postgres -q -c "ALTER ROLE ${from}_mail_$r RENAME TO ${to}_mail_$r" >/dev/null || return 1
    fi
    printf "ALTER ROLE %s PASSWORD :'pw';\n" "${to}_mail_$r" |
      compose exec -T mail-db psql -v ON_ERROR_STOP=1 -U mailadmin -d postgres -q -v pw="$(cat "$ETC/secrets/mail-db-$r")" >/dev/null || return 1
  done
  # MariaDB's provisioning account (a rename keeps its password and grants)
  # and the control plane's record of it.
  if [ -s "$ETC/secrets/mariadb-root" ]; then
    compose exec -T -e FROM="${from}_prov" -e TO="${to}_prov" mariadb sh -c 'MYSQL_PWD="$(cat /run/scalpanel-db/mariadb-root 2>/dev/null || cat /run/vpanel-db/mariadb-root 2>/dev/null || printf %s "$MARIADB_ROOT_PASSWORD")"
      export MYSQL_PWD
      if [ "$(mariadb -uroot -N -e "SELECT COUNT(*) FROM mysql.user WHERE User = '"'"'$FROM'"'"'")" != 0 ]; then
        mariadb -uroot -e "RENAME USER '"'"'$FROM'"'"'@'"'"'%'"'"' TO '"'"'$TO'"'"'@'"'"'%'"'"'"
      fi' || return 1
    compose exec -T postgres psql -v ON_ERROR_STOP=1 -U "$to" -d "$to" -q \
      -c "UPDATE database_servers SET admin_user = '${to}_prov' WHERE name = 'main' AND host = 'mariadb' AND admin_user = '${from}_prov'" >/dev/null || return 1
  fi
}

# The volumes that keep their vPanel names are the ones compose.volumes.yaml
# maps; nothing else moves (a server installed as ScalPanel has none, and a
# stray vpanel_* volume is not in use). One "key old-name" per line.
names_volumes() {
  [ -s "$ETC/compose.volumes.yaml" ] || return 0
  awk '/^  [a-z0-9][a-z0-9_-]*:$/ { k = substr($1, 1, length($1) - 1) }
    /^    name: / && k != "" { print k, $2; k = "" }' "$ETC/compose.volumes.yaml"
}

# Before anything moves: every old volume is there and local, and its
# ScalPanel volume is missing or empty.
names_volumes_check() { # list
  local key old mp
  while read -r key old; do
    [[ "$key" =~ ^[a-z0-9][a-z0-9_-]*$ ]] && [[ "$old" =~ ^[a-z0-9][a-z0-9_.-]*$ ]] ||
      { log "compose.volumes.yaml names an unexpected volume: $key $old"; return 1; }
    [ "$(docker volume inspect -f '{{.Driver}}' "$old" 2>/dev/null)" = local ] ||
      { log "the volume $old is missing or not a local volume"; return 1; }
    if docker volume inspect "scalpanel_$key" >/dev/null 2>&1; then
      mp=$(docker volume inspect -f '{{.Mountpoint}}' "scalpanel_$key") || return 1
      [ -z "$(ls -A "$mp")" ] || { log "the volume scalpanel_$key already holds data"; return 1; }
    fi
  done < "$1"
}

# Moves the listed volumes' data to their ScalPanel volumes (a rename on the
# same filesystem), or back.
move_volumes() { # list to|back
  local key old src dst src_mp dst_mp
  while read -r key old; do
    if [ "$2" = to ]; then src=$old dst=scalpanel_$key; else src=scalpanel_$key dst=$old; fi
    docker volume inspect "$src" >/dev/null 2>&1 || continue
    docker volume inspect "$dst" >/dev/null 2>&1 ||
      docker volume create --label com.docker.compose.project=scalpanel --label "com.docker.compose.volume=$key" "$dst" >/dev/null || return 1
    src_mp=$(docker volume inspect -f '{{.Mountpoint}}' "$src") && dst_mp=$(docker volume inspect -f '{{.Mountpoint}}' "$dst") || return 1
    [ "$(stat -c %d "$src_mp")" = "$(stat -c %d "$dst_mp")" ] || { log "the volumes $src and $dst are on different filesystems"; return 1; }
    # The volume's own directory keeps its owner and mode: Docker copies
    # them from the image only into an empty volume (the panel's
    # certificates are written by its user, PostgreSQL wants 1777).
    chown --reference="$src_mp" "$dst_mp" && chmod --reference="$src_mp" "$dst_mp" || return 1
    find "$src_mp" -mindepth 1 -maxdepth 1 -exec mv -t "$dst_mp" -- {} + || return 1
  done < "$1"
}

# Runs the move when the server is ready for it: on the ScalPanel layout,
# its release fully installed and one that knows both names. Called with the
# update lock held.
names_move_when_ready() { # [force]
  local cur ver
  [ "$NAMES" = scalpanel ] && [ ! -e "$ETC/.names-moving" ] && return 0
  old_layout && return 1
  cur=$(readlink -f "$OPT/current" 2>/dev/null || true)
  ver=$(installed_version)
  if [ -z "$cur" ] || [ "$(basename "$cur")" != "$ver" ] || ! grep -q 'SCALPANEL_NAMES:-' "$cur/compose.yaml" 2>/dev/null; then
    log "the database names move after the update has finished"
    return 1
  fi
  if [ -e "$LIB/state/names-move-failed" ] && [ "${1:-}" != force ] && [ ! -e "$ETC/.names-moving" ]; then
    log "the move to the ScalPanel database names failed before; retry with: scalpanelctl move-names"
    return 1
  fi
  rm -f "$LIB/state/names-move-failed"
  names_move "$ver"
}

set_names() { # names: the settings file and the password file
  NAMES=$1
  if grep -q '^SCALPANEL_NAMES=' "$ENV_FILE"; then
    sed -i "s/^SCALPANEL_NAMES=.*/SCALPANEL_NAMES=$1/" "$ENV_FILE"
  else
    echo "SCALPANEL_NAMES=$1" >> "$ENV_FILE"
  fi
  write_pgpass
}

names_move() { # version
  local ver=$1 phase=dbs list=$LIB/state/names-volumes
  trap '' INT HUP
  STATUS_VERSION=$ver
  mkdir -p "$LIB/state"
  # An interrupted move goes on where it stopped: once the volumes move, the
  # databases never start on a half-moved volume.
  [ -e "$ETC/.names-moving" ] && phase=$(sed -n 2p "$ETC/.names-moving")
  [ "$phase" = volumes ] && [ -e "$list" ] || phase=dbs
  if [ "$phase" = dbs ]; then
    # Nothing changes unless every volume can move.
    names_volumes > "$list"
    if ! names_volumes_check "$list"; then
      rm -f "$list" "$ETC/.names-moving"
      touch "$LIB/state/names-move-failed"
      status failed "the move to the ScalPanel names cannot start; nothing was changed (see scalpanelctl move-names)"
      die "the move to the ScalPanel names cannot start; nothing was changed"
    fi
    if [ -s "$ETC/compose.volumes.yaml" ]; then
      cp -p "$ETC/compose.volumes.yaml" "$LIB/state/compose.volumes.yaml.before-names"
    fi
  fi
  printf '%s\n%s\n' "$ver" "$phase" > "$ETC/.names-moving"
  log "moving the databases and volumes to the ScalPanel names (ADR-0201); the panels stop for a few minutes"
  status installing "renaming the databases and volumes to ScalPanel; the panels are back in a few minutes"
  local ok=1
  if [ "$phase" = dbs ]; then
    { compose stop >/dev/null 2>&1 && compose up -d postgres mail-db mariadb && wait_healthy 300 postgres mail-db mariadb &&
      rename_dbs vpanel scalpanel && compose down --remove-orphans; } || ok=0
    [ $ok = 1 ] && phase=volumes && printf '%s\nvolumes\n' "$ver" > "$ETC/.names-moving"
  else
    compose down --remove-orphans >/dev/null 2>&1 || true
  fi
  if [ $ok = 1 ] && move_volumes "$list" to; then
    rm -f "$ETC/compose.volumes.yaml"
    set_names scalpanel
    if compose up -d --remove-orphans && wait_healthy 600 api worker webmail-api mail panel node; then
      # The old volumes are empty now.
      while read -r _ old; do docker volume rm "$old" >/dev/null 2>&1 || true; done < "$list"
      rm -f "$ETC/.names-moving" "$list" "$LIB/state/compose.volumes.yaml.before-names"
      [ -L /usr/local/sbin/vpanelctl ] && rm -f /usr/local/sbin/vpanelctl
      trap - INT HUP
      status "done" "ScalPanel $ver: the databases and volumes have the ScalPanel names"
      log "moved: databases scalpanel and scalpanel_mail, their roles, scalpanel_prov and the volumes"
      return 0
    fi
  fi
  log "the move to the ScalPanel database names failed; going back"
  compose down --remove-orphans >/dev/null 2>&1 || true
  # Only the volumes this move took go back.
  if [ "$phase" = volumes ] && ! move_volumes "$list" back; then
    status failed "the volumes could not be moved back; see docker volume ls (scalpanel_* and vpanel_*)"
    die "the volumes could not all be moved back: move the data of each volume in $list back, then run scalpanelctl move-names"
  fi
  if [ -s "$LIB/state/compose.volumes.yaml.before-names" ]; then
    install -m 0644 "$LIB/state/compose.volumes.yaml.before-names" "$ETC/compose.volumes.yaml"
  fi
  if compose up -d postgres mail-db mariadb && wait_healthy 300 postgres mail-db mariadb; then
    rename_dbs scalpanel vpanel || log "the database names could not all be restored"
  fi
  set_names vpanel
  compose up -d --remove-orphans || true
  touch "$LIB/state/names-move-failed"
  rm -f "$ETC/.names-moving" "$list"
  die "the move to the ScalPanel database names failed and was undone (retry: scalpanelctl move-names)"
}

names_from_request() {
  [ -e "$UPDATE_DIR/names-request.json" ] || [ -e "$ETC/.names-moving" ] || return 0
  rm -f -- "$UPDATE_DIR/names-request.json"
  # In a subshell: a failure (die) ends this request only.
  ( names_move_when_ready ) || true
}

# ---------------------------------------------------------------- add-ons
# ScalGuard (ADR-0177), SCB Network's security platform: its agent on this
# host, its control plane and database in this installation's compose
# project, provisioned and connected to the panel. Everything comes from
# ScalGuard's own signed release channel, checked against its root key
# pinned here (key id 8047ff41404812ca):
#   keyring.json   DSSE, signed by the root key: the online keys
#   manifest.json  DSSE, two keyring keys (kind agent): every file by SHA-256
#   <v>/release.json  which package and image are for what
SG_ROOT_KEY="KMLahmO/p5lxs3GWCoG6fNdJiEziqxs/4hFFC+PavNc=" # gitleaks:allow (a public key)
SG_URL=$(setting SCALGUARD_RELEASE_URL https://guard.scalws.com/releases/stable)
# The operator API version this ScalPanel reads (ADR-0175).
SG_API=1
SG_DIR=$ETC/addons/scalguard
SG_STATE=$LIB/state/scalguard
SG_OVERRIDE=$ETC/compose.scalguard.yaml
SG_REQUEST=""

sg_version() { cat "$SG_DIR/version" 2>/dev/null || echo none; }

# addon-status.json for the panel: version is the request, current the
# installed ScalGuard version.
sg_status() { # state message [percent]
  case "$1" in done | failed) SG_FINISHED=1 ;; esac
  [ -n "$SG_REQUEST" ] && [ -d "$UPDATE_DIR" ] || return 0
  install -d -o root -g root -m 0755 "$STATUS_DIR" || return 0
  local tmp
  tmp=$(mktemp "$STATUS_DIR/.addon-status.XXXXXX") || return 0
  local pct=null
  [[ "${3:-}" =~ ^[0-9]+$ ]] && [ "$3" -le 100 ] && pct=$3
  jq -cn --arg s "$1" --arg r "$SG_REQUEST" --arg c "$(sg_version)" --arg m "${2:0:1500}" --argjson p "$pct" \
    --arg t "$(date -u +%Y-%m-%dT%H:%M:%SZ)" '{state:$s, version:$r, current:$c, message:$m, updated_at:$t}
      + (if $p == null then {} else {progress:$p} end)' > "$tmp"
  chmod 0644 "$tmp"
  mv -fT "$tmp" "$STATUS_DIR/addon-status.json"
}
sg_die() { log "error: $*"; sg_status failed "$*"; exit 1; }

sg_fetch() { # path dest max-bytes
  curl -fsSL --proto =https --retry 3 --retry-delay 2 --connect-timeout 20 --max-filesize "$3" -o "$2" "$SG_URL/$1"
}

# A raw base64 Ed25519 key as PEM (the 12-byte DER header is a multiple of
# 3, so the two base64 strings simply concatenate) and its key id.
sg_key() { # base64 dir
  [[ "$1" =~ ^[A-Za-z0-9+/]{43}=$ ]] || return 1
  local id
  id=$(printf '%s' "$1" | base64 -d | sha256sum | cut -c1-16)
  printf -- '-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA%s\n-----END PUBLIC KEY-----\n' "$1" > "$2/$id.pem"
}

# A DSSE envelope signed by at least <need> distinct keys of <keys>/<id>.pem;
# its payload is left in <env>.payload.
sg_dsse() { # env type need keys
  local env=$1 type=$2 need=$3 keys=$4 n i kid good=0 seen=" "
  [ "$(jq -r .payloadType "$env" 2>/dev/null)" = "$type" ] || return 1
  jq -r .payload "$env" | base64 -d > "$env.payload" 2>/dev/null || return 1
  { printf 'DSSEv1 %d %s %d ' "${#type}" "$type" "$(stat -c %s "$env.payload")"; cat "$env.payload"; } > "$env.pae"
  n=$(jq '.signatures | length' "$env")
  for ((i = 0; i < n && i < 8; i++)); do
    kid=$(jq -r ".signatures[$i].keyid" "$env")
    [[ "$kid" =~ ^[0-9a-f]{16}$ ]] && [ -f "$keys/$kid.pem" ] || continue
    case "$seen" in *" $kid "*) continue ;; esac
    jq -r ".signatures[$i].sig" "$env" | base64 -d > "$env.sig" 2>/dev/null || continue
    openssl pkeyutl -verify -pubin -inkey "$keys/$kid.pem" -rawin -in "$env.pae" -sigfile "$env.sig" >/dev/null 2>&1 || continue
    seen="$seen$kid "; good=$((good + 1))
  done
  [ "$good" -ge "$need" ]
}

sg_future() { # RFC 3339 time: is it after now?
  local t
  t=$(date -u -d "$1" +%s 2>/dev/null) && [ "$t" -gt "$(date -u +%s)" ]
}

# Never back: a lower version than one accepted before is refused, and the
# same manifest version must have the same content.
sg_not_older() { # name version [sha256]
  local f="$SG_STATE/$1" prev
  [[ "$2" =~ ^[0-9]{1,12}$ ]] || return 1
  prev=$(cat "$f" 2>/dev/null || echo "0 -")
  [ "$2" -gt "${prev%% *}" ] || { [ "$2" -eq "${prev%% *}" ] && [ "${3:--}" = "${prev#* }" ]; }
}
sg_accept() { # name version [sha256]
  printf '%s %s\n' "$2" "${3:--}" > "$SG_STATE/$1.tmp" && mv -f "$SG_STATE/$1.tmp" "$SG_STATE/$1"
}

# Reads and checks the channel; sets SG_V (the version) and leaves
# $WORK/sg/release.json.
sg_release() {
  local d=$WORK/sg kv kring man rel k
  install -d -m 0700 "$d" "$d/root" "$d/keys"
  install -d -m 0700 "$SG_STATE"
  sg_key "$SG_ROOT_KEY" "$d/root" || sg_die "the pinned ScalGuard root key is invalid"
  sg_fetch keyring.json "$d/keyring.json" 1048576 || sg_die "cannot read ScalGuard's release channel ($SG_URL)"
  sg_dsse "$d/keyring.json" application/vnd.scalguard.keyring.v1+json 1 "$d/root" ||
    sg_die "ScalGuard's keyring is not signed by its root key: refusing to continue"
  kring=$d/keyring.json.payload
  sg_future "$(jq -r .expires_at "$kring")" || sg_die "ScalGuard's keyring has expired"
  kv=$(jq -r .version "$kring")
  sg_not_older keyring "$kv" || sg_die "ScalGuard's keyring is older than one seen before"
  for k in $(jq -r '.keys[] | select((.kinds | index("agent")) and (.expires_at | type) == "string") | .public_key + " " + .expires_at' "$kring" |
    awk '{print $1 "|" $2}'); do
    sg_future "${k#*|}" && sg_key "${k%%|*}" "$d/keys" || true
  done
  sg_fetch manifest.json "$d/manifest.json" 4194304 || sg_die "cannot read ScalGuard's release manifest"
  sg_dsse "$d/manifest.json" application/vnd.scalguard.manifest.v1+json 2 "$d/keys" ||
    sg_die "ScalGuard's release manifest lacks two valid signatures: refusing to continue"
  man=$d/manifest.json.payload
  [ "$(jq -r .kind "$man")" = agent ] && [ "$(jq -r .channel "$man")" = stable ] || sg_die "ScalGuard's manifest is for another channel"
  sg_future "$(jq -r .expires_at "$man")" || sg_die "ScalGuard's release manifest has expired"
  sg_not_older manifest "$(jq -r .version "$man")" "$(sha256_of "$man")" || sg_die "ScalGuard's release manifest is older than one seen before"
  # The newest release descriptor in it.
  rel=$(jq -r '.artifacts[].path | select(test("^[0-9]+\\.[0-9]+\\.[0-9]+/release\\.json$"))' "$man" | sort -V | tail -1)
  [ -n "$rel" ] || sg_die "ScalGuard's manifest names no release"
  SG_V=${rel%/release.json}
  sg_artifact "$rel" "$d/release.json" 1048576
  jq -e --argjson api "$SG_API" '.schema <= 1 and .version == "'"$SG_V"'" and .api_version == $api' "$d/release.json" >/dev/null ||
    sg_die "ScalGuard $SG_V needs a newer ScalPanel (operator API $(jq -r .api_version "$d/release.json"))"
  sg_accept keyring "$kv"
  sg_accept manifest "$(jq -r .version "$man")" "$(sha256_of "$man")"
}

# Downloads one file of the release and checks it against the manifest.
sg_size() { # path: its size in the signed manifest
  jq -r --arg p "$1" '.artifacts[] | select(.path == $p) | .size' "$WORK/sg/manifest.json.payload"
}

# With <from> and <to>, the download reports its progress in percent.
sg_artifact() { # path dest max-bytes [from to]
  local want size pid got
  [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+/[A-Za-z0-9._+-]+$ ]] || sg_die "a bad file name in ScalGuard's release: $1"
  want=$(jq -r --arg p "$1" '.artifacts[] | select(.path == $p) | .sha256' "$WORK/sg/manifest.json.payload")
  size=$(sg_size "$1")
  [[ "$want" =~ ^[0-9a-f]{64}$ ]] && [[ "$size" =~ ^[0-9]+$ ]] || sg_die "$1 is not in ScalGuard's signed manifest"
  if [ -z "${5:-}" ]; then
    sg_fetch "$1" "$2" "$3" || sg_die "cannot download $1"
    [ "$(stat -c %s "$2")" = "$size" ] && [ "$(sha256_of "$2")" = "$want" ] || sg_die "$1 does not match ScalGuard's signed manifest"
    return 0
  fi
  sg_fetch "$1" "$2" "$3" &
  pid=$!
  while kill -0 "$pid" 2>/dev/null; do
    got=$(stat -c %s "$2" 2>/dev/null || echo 0)
    [ "$got" -le "$size" ] || got=$size
    sg_status installing "Downloading ScalGuard $SG_V" $(($4 + ($5 - $4) * got / (size > 0 ? size : 1)))
    sleep 2
  done
  wait "$pid" || sg_die "cannot download $1"
  [ "$(stat -c %s "$2")" = "$size" ] && [ "$(sha256_of "$2")" = "$want" ] || sg_die "$1 does not match ScalGuard's signed manifest"
}

# The control plane's compose services. Its database uses this
# installation's PostgreSQL image when ScalGuard supports its major version.
sg_compose_file() { # image postgres-image
  local host
  host=$(setting SCALPANEL_HOSTNAME "")
  [ -n "$host" ] || sg_die "SCALPANEL_HOSTNAME is not set"
  cat > "$SG_OVERRIDE.tmp" <<EOF
# The ScalGuard add-on (ADR-0177), written by scalpanelctl: do not edit.
services:
  scalguard-db:
    image: $2
    restart: unless-stopped
    logging: { driver: json-file, options: { max-size: "20m", max-file: "5" } }
    environment:
      POSTGRES_USER: scalguard
      POSTGRES_DB: scalguard
      POSTGRES_PASSWORD_FILE: /run/scalguard-db/password
    volumes:
      - scalguard-pgdata:/var/lib/postgresql
      - $SG_DIR/db:/run/scalguard-db:ro
    networks: [scalguard]
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "scalguard", "-d", "scalguard"]
      interval: 3s
      timeout: 3s
      retries: 40

  scalguard-control:
    image: $1
    pull_policy: never
    restart: unless-stopped
    logging: { driver: json-file, options: { max-size: "20m", max-file: "5" } }
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    environment:
      SCALGUARD_DATABASE_URL: postgres://scalguard@scalguard-db:5432/scalguard
      SCALGUARD_DATABASE_PASSWORD_FILE: /run/scalguard/db-password
      SCALGUARD_SECRET_KEY_FILE: /run/scalguard/secret-key
      # The panel's TLS edge is the only proxy (its fixed address).
      SCALGUARD_TRUSTED_PROXIES: 10.231.0.10/32
      SCALGUARD_PUBLIC_URL: https://$host:8790
    volumes:
      - $SG_DIR/control:/run/scalguard:ro
    # The agent on this host connects here; nothing else outside.
    ports: ["127.0.0.1:8700:8700"]
    networks: [default, scalguard]
    depends_on:
      scalguard-db: { condition: service_healthy }

  # The console, over the panel's TLS.
  panel:
    ports: ["8790:8790"]

networks:
  scalguard:
    internal: true

volumes:
  scalguard-pgdata:
EOF
  chmod 0644 "$SG_OVERRIDE.tmp"
  mv -f "$SG_OVERRIDE.tmp" "$SG_OVERRIDE"
}

sg_install() { # email organization
  local d=$WORK/sg os ver arch deb img pg pgmajor out rc tries
  sg_status installing "Checking ScalGuard's signed release" 2
  sg_release
  log "installing ScalGuard $SG_V"

  # The agent package for this system.
  . /etc/os-release
  os=${ID:-} ver=${VERSION_ID:-}
  arch=$(dpkg --print-architecture 2>/dev/null || echo unknown)
  deb=$(jq -r --arg os "$os" --arg v "$ver" --arg a "$arch" '[.agent[] | select(.format == "deb" and .arch == $a and
      any(.platforms[]; .os == $os and (.versions | index($v))))][0].path // empty' "$d/release.json")
  [ -n "$deb" ] || sg_die "ScalGuard $SG_V has no agent package for $os $ver ($arch)"
  img=$(jq -r '.control_plane.image | select(.format == "docker-archive" and .platform == "linux/amd64") | .path // empty' "$d/release.json")
  [ -n "$img" ] && [ "$arch" = amd64 ] || sg_die "ScalGuard $SG_V has no control-plane image for this server"
  local image_id
  image_id=$(jq -r '.control_plane.image.image_id' "$d/release.json")
  [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || sg_die "ScalGuard's release names no image ID"
  pg=$(awk '/^  postgres:/{f=1} f && /image:/{print $2; exit}' "$OPT/current/compose.yaml")
  pgmajor=$(printf '%s' "$pg" | sed -n 's/^postgres:\([0-9][0-9]*\)-.*/\1/p')
  jq -e --argjson m "${pgmajor:-0}" '.control_plane.postgres | .min_major <= $m and (.tested_majors | index($m))' "$d/release.json" >/dev/null ||
    sg_die "ScalGuard $SG_V is not tested with this server's PostgreSQL ($pg)"

  # Downloads: 5-70 %, shared by size.
  local sd si mid
  sd=$(sg_size "$SG_V/$deb") si=$(sg_size "$SG_V/$img")
  [[ "$sd" =~ ^[0-9]+$ ]] && [[ "$si" =~ ^[0-9]+$ ]] || sg_die "ScalGuard's files are not in its signed manifest"
  mid=$((5 + 65 * sd / (sd + si > 0 ? sd + si : 1)))
  sg_artifact "$SG_V/$deb" "$d/agent.deb" 268435456 5 "$mid"
  sg_artifact "$SG_V/$img" "$d/image.tar.gz" 1073741824 "$mid" 70
  [ "$(sha256_of "$d/agent.deb")" = "$(jq -r --arg p "$deb" '.agent[] | select(.path == $p) | .sha256' "$d/release.json")" ] &&
    [ "$(sha256_of "$d/image.tar.gz")" = "$(jq -r '.control_plane.image.sha256' "$d/release.json")" ] ||
    sg_die "ScalGuard's release descriptor and manifest disagree"
  sg_status installing "Loading ScalGuard's image" 72
  docker load -i "$d/image.tar.gz" >/dev/null || sg_die "the ScalGuard image does not load"
  docker image inspect "$image_id" >/dev/null 2>&1 || sg_die "the ScalGuard image is not the one its release names"
  docker tag "$image_id" "scalguard-control:$SG_V"

  # Secrets: the database's own password, readable by its user in the
  # container; the control plane's (UID 10001) password and sealing key;
  # tokens and the console password for root alone.
  sg_status installing "Starting ScalGuard" 78
  install -d -m 0700 "$SG_DIR"
  install -d -m 0755 "$SG_DIR/db"
  install -d -o 10001 -g 10001 -m 0700 "$SG_DIR/control"
  [ -s "$SG_DIR/control/db-password" ] || { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$SG_DIR/control/db-password"; }
  [ -s "$SG_DIR/control/secret-key" ] || { head -c 32 /dev/urandom | base64 > "$SG_DIR/control/secret-key"; }
  install -m 0644 "$SG_DIR/control/db-password" "$SG_DIR/db/password"
  chown 10001:10001 "$SG_DIR/control/db-password" "$SG_DIR/control/secret-key"
  chmod 0400 "$SG_DIR/control/db-password" "$SG_DIR/control/secret-key"
  sg_compose_file "scalguard-control:$SG_V" "$pg"
  compose up -d scalguard-db scalguard-control panel || sg_die "ScalGuard did not start; see: scalpanelctl compose ps"
  wait_healthy 300 scalguard-db scalguard-control || sg_die "ScalGuard did not become healthy within 5 minutes"

  # Provisioning: the organisation, the panel's read-only token, the
  # agent's enrollment token and the console's administrator. Idempotent:
  # a later run issues nothing and writes no file.
  sg_status installing "Setting ScalGuard up" 88
  out=$(mktemp -d "$WORK/sg-out.XXXXXX"); chown 10001:10001 "$out"; chmod 0700 "$out"
  for tries in 1 2 3 4 5 6 7 8 9 10; do
    rc=0
    compose run --rm --no-deps -T -v "$out:/out" scalguard-control provision --organization="$2" --panel scalpanel \
      --panel-token-file /out/panel-token --enrollment-token-file /out/enroll-token --actor-token-file /out/actor-token \
      --admin-email="$1" --admin-password-file /out/admin-password --enrollment-expires-hours 0 >/dev/null || rc=$?
    [ $rc = 75 ] || break
    sleep 6
  done
  [ $rc = 0 ] || sg_die "ScalGuard's provisioning failed (exit $rc)"
  local f
  for f in panel-token enroll-token actor-token admin-password; do
    [ -s "$out/$f" ] || continue
    install -m 0600 -o root -g root "$out/$f" "$SG_DIR/$f"
  done
  rm -rf "$out"
  [ -s "$SG_DIR/panel-token" ] && [ -s "$SG_DIR/enroll-token" ] || sg_die "ScalGuard issued no tokens and none are kept here"
  # The token, the console's first password (the panel signs the provider
  # in with it, ADR-0180) and the actor token (scans from the panels, ADR-0182).
  # One per line ($(…) drops a file's own newline; printf is a builtin, so
  # nothing shows in the process list).
  printf '%s\n%s\n%s\n' "$(cat "$SG_DIR/panel-token")" "$(cat "$SG_DIR/admin-password" 2>/dev/null || true)" \
    "$(cat "$SG_DIR/actor-token" 2>/dev/null || true)" |
    admin scalguard-connect http://scalguard-control:8700 >/dev/null || sg_die "the panel did not take ScalGuard's connection"

  # The agent: our own configuration (the package's lists actions the panel
  # owns), then enrollment with the local control plane.
  sg_status installing "Installing the ScalGuard agent" 94
  install -d -m 0755 /etc/scalguard
  jq -n '{control_url: "http://127.0.0.1:8700", allow_insecure_http: true}' > /etc/scalguard/agent.json.scalpanel
  chmod 0600 /etc/scalguard/agent.json.scalpanel
  DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y -q -o Dpkg::Options::=--force-confold "$d/agent.deb" >/dev/null ||
    sg_die "the ScalGuard agent package did not install"
  mv -f /etc/scalguard/agent.json.scalpanel /etc/scalguard/agent.json
  if ! scalguard-agent enroll --token-file "$SG_DIR/enroll-token" --url http://127.0.0.1:8700 > "$WORK/enroll.log" 2>&1 &&
    ! grep -q "already enrolled" "$WORK/enroll.log"; then
    sg_die "the ScalGuard agent did not enroll: $(tail -c 300 "$WORK/enroll.log")"
  fi
  systemctl try-restart scalguard-agent.service >/dev/null 2>&1 || true

  printf '%s\n' "$SG_V" > "$SG_DIR/version"
  sg_status "done" "ScalGuard $SG_V installed" 100
  log "ScalGuard $SG_V installed; console https://$(setting SCALPANEL_HOSTNAME localhost):8790"
}

sg_uninstall() { # delete-data (0/1)
  sg_status installing "Removing ScalGuard" 10
  if command -v scalguard-agent >/dev/null 2>&1; then
    scalguard-agent uninstall --keep-quarantine >/dev/null 2>&1 || true
    DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 purge -y -q scalguard-agent >/dev/null 2>&1 || sg_die "the ScalGuard agent package did not uninstall"
  fi
  admin scalguard-connect '' >/dev/null 2>&1 || true
  sg_status installing "Removing ScalGuard's services" 50
  if [ -s "$SG_OVERRIDE" ]; then
    compose rm -sf scalguard-control scalguard-db >/dev/null 2>&1 || true
    rm -f "$SG_OVERRIDE"
    # The panel without the console's port.
    compose up -d panel >/dev/null 2>&1 || true
  fi
  if [ "$1" = 1 ]; then
    docker volume rm "${PROJECT}_scalguard-pgdata" >/dev/null 2>&1 || true
    rm -rf "$SG_DIR"
  else
    # Kept: the database volume and the secrets that open it.
    rm -f "$SG_DIR/version"
  fi
  sg_status "done" "ScalGuard removed" 100
  log "ScalGuard removed"
}

cmd_addon() {
  local sub=${1:-} name=${2:-} email="" org="ScalPanel" del=0
  [ $# -gt 0 ] && shift
  [ $# -gt 0 ] && shift
  while [ $# -gt 0 ]; do
    case "$1" in
      --email) email=${2:-}; shift ;;
      --organization) org=${2:-}; shift ;;
      --delete-data) del=1 ;;
      *) die "unknown option $1" ;;
    esac
    shift
  done
  case "$sub $name" in
    "status ") echo "scalguard $(sg_version)"; return 0 ;;
    "install scalguard"|"uninstall scalguard") ;;
    *) die "usage: scalpanelctl addon install scalguard --email <e-mail> [--organization <name>] | uninstall scalguard [--delete-data] | status" ;;
  esac
  exec 9>"$LOCK"
  flock -n 9 || die "an update or installation is running"
  WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
  sg_run "$sub" "$email" "$org" "$del"
}

sg_run() { # action email organization delete-data
  case "$1" in
    install)
      [[ "$2" =~ ^[^[:space:]\<\>\"]{1,254}$ ]] && [[ "$2" == *@*.* ]] || sg_die "an e-mail address for the console's administrator is needed"
      [[ "$3" =~ ^[^[:cntrl:]]{1,128}$ ]] || sg_die "invalid organization name"
      sg_install "$2" "$3" ;;
    uninstall) sg_uninstall "$4" ;;
  esac
}

# The panel's add-on request (ADR-0177), taken like an update request.
addon_from_request() {
  install -d -o root -g root -m 0755 "$STATUS_DIR"
  local req="$STATUS_DIR/.addon-request.$$" id action email org del
  mv -fT -- "$UPDATE_DIR/addon-request.json" "$req" 2>/dev/null || return 0
  if [ -L "$req" ] || [ ! -f "$req" ] || [ "$(stat -c %s "$req")" -gt 4096 ]; then rm -f -- "$req"; return 0; fi
  if ! jq -e '.addon == "scalguard" and (.action == "install" or .action == "uninstall") and (.id | type) == "string"' < "$req" >/dev/null 2>&1; then
    rm -f -- "$req"; return 0
  fi
  id=$(jq -r .id < "$req"); action=$(jq -r .action < "$req"); email=$(jq -r '.email // ""' < "$req")
  org=$(jq -r '.organization // "ScalPanel"' < "$req"); del=$(jq -r 'if .delete_data == true then 1 else 0 end' < "$req")
  rm -f -- "$req"
  [[ "$id" =~ ^job_[0-9A-HJKMNP-TV-Z]{26}$ ]] || return 0
  # In a subshell: a failure (sg_die) ends that request only.
  # An unexpected stop still ends the request for the panel.
  ( SG_REQUEST=$id; WORK=$(mktemp -d)
    trap 'rc=$?; [ $rc = 0 ] || [ -n "${SG_FINISHED:-}" ] ||
      sg_status failed "ScalGuard'"'"'s installer stopped (exit $rc); see: journalctl -u scalpanel-update"; rm -rf "$WORK"' EXIT
    sg_run "$action" "$email" "$org" "$del" ) || true
}

# ---------------------------------------------------------------- disk
# Every release adds its images; nothing took the old ones away, and a
# small disk filled up (ADR-0205). Images no container uses go: the
# platform's on the host, the old runtimes and sessions in the node.
# A container's image is never removed (docker refuses), and an older
# release's images come back from the local registry if needed.
prune_images() {
  local before after ref keep
  before=$(df -Pk /var/lib/docker 2>/dev/null | awk 'NR==2{print $4}')
  # The host: the platform's images from the local registry.
  docker image ls --digests --format '{{.Repository}} {{.Digest}} {{.ID}}' 2>/dev/null |
    awk '$1 ~ /^127\.0\.0\.1:5000\// { print ($2 != "<none>" ? $1 "@" $2 : $3) }' | sort -u |
    while read -r ref; do docker image rm "$ref" </dev/null >/dev/null 2>&1 || true; done
  # The node: runtime and session images other than this release's.
  # (An updater before 0.1.30 may have written the VPANEL_ names.)
  keep=$(sed -n -E 's/^(SCALPANEL|VPANEL)_(RUNTIME_IMAGES|SESSION_IMAGE)=//p' "$ETC/release.env" 2>/dev/null | tr ',' '\n' | sed 's/^[^=]*=//')
  compose exec -T node docker image ls --digests --format '{{.Repository}}@{{.Digest}}' 2>/dev/null | tr -d '\r' |
    { grep '^registry:5000/' || true; } | while read -r ref; do
      printf '%s\n' "$keep" | grep -qxF "$ref" && continue
      case "$ref" in */busybox@*) continue ;; esac # the workload image
      compose exec -T node docker image rm "$ref" </dev/null >/dev/null 2>&1 || true
    done
  after=$(df -Pk /var/lib/docker 2>/dev/null | awk 'NR==2{print $4}')
  if [ -n "$before" ] && [ -n "$after" ] && [ "$after" -gt "$before" ]; then
    log "old images removed: $(( (after - before) / 1024 )) MiB freed"
  fi
}

# Free space (KiB) on the filesystem holding a path.
free_kib() { df -Pk "$1" 2>/dev/null | awk 'NR==2{print $4}'; }

# Before a download of <bytes>: the registry keeps them, and Docker unpacks
# part of the images again: twice that and 1 GiB to spare, on both
# filesystems. Old images go first when that is short.
need_space() { # bytes what
  local need=$(( $1 / 1024 * 2 + 1048576 )) p free short=""
  mkdir -p "$LIB/registry"
  for p in "$LIB/registry" /var/lib/docker; do
    free=$(free_kib "$p"); [ -n "$free" ] && [ "$free" -lt "$need" ] && short=1
  done
  [ -z "$short" ] && return 0
  log "little free disk space for $2; removing old images first"
  prune_images
  for p in "$LIB/registry" /var/lib/docker; do
    free=$(free_kib "$p")
    if [ -n "$free" ] && [ "$free" -lt "$need" ]; then
      status failed "not enough free disk space for $2: $((free / 1024)) MiB free on $(df -P "$p" | awk 'NR==2{print $6}'), $((need / 1024)) MiB needed. Nothing was changed."
      die "not enough free disk space for $2 on $(df -P "$p" | awk 'NR==2{print $6}'): $((free / 1024)) MiB free, $((need / 1024)) MiB needed; nothing was changed"
    fi
  done
}

# ---------------------------------------------------------------- status
cmd_status() {
  echo "ScalPanel $(installed_version) (channel $CHANNEL, $UPDATE_URL)"
  [ -f "$STATUS_DIR/status.json" ] && [ ! -L "$STATUS_DIR/status.json" ] && echo "last update: $(cat "$STATUS_DIR/status.json")"
  compose ps --format 'table {{.Service}}\t{{.State}}\t{{.Status}}'
  local ip; ip=$(setting SCALPANEL_PUBLIC_IP "")
  if [ -n "$ip" ] && host_ipv4s | grep -q . && ! host_ipv4s | grep -qxF "$ip"; then
    echo "warning: $ip (SCALPANEL_PUBLIC_IP) is not an address of this server; if it changed: scalpanelctl set-ip <new address>"
  fi
}

[ "$(id -u)" = 0 ] || { echo "scalpanelctl must run as root" >&2; exit 1; }
cmd=${1:-status}; shift || true
# A server installed as vPanel moves to the ScalPanel names (ADR-0174): from
# the update path unit, or now with move-layout. An interrupted move is
# finished first, whatever the command.
if [ -e "$MOVING" ] && [ "$cmd" != version ]; then
  layout_move_when_ready || exit 1
elif old_layout; then
  case "$cmd" in
    move-layout) layout_move_when_ready force || exit 1; exit 0 ;;
    update)
      if [ "${1:-}" = --from-request ] && ! layout_move_when_ready &&
        [ ! -e "$UPDATE_DIR/request.json" ] && [ ! -e "$UPDATE_DIR/runtime-request.json" ] && [ ! -e "$UPDATE_DIR/service-request.json" ] &&
        [ ! -e "$UPDATE_DIR/addon-request.json" ]; then
        # Started by vpanel-update.path for the move only: not now, and not
        # again at once (the path unit starts this while its path exists).
        sleep 300; exit 0
      fi ;;
  esac
fi
scripts_link || true
rename_settings || true
case "$cmd" in
  install) cmd_install "$@" ;;
  move-names)
    exec 9>"$LOCK"
    flock -w 7000 9 || die "an update is running; try again later"
    names_move_when_ready force ;;
  update) cmd_update "$@" ;;
  runtime) cmd_runtime "$@" ;;
  addon) cmd_addon "$@" ;;
  status) cmd_status ;;
  compose) compose "$@" ;;
  admin) admin "$@" ;;
  logs) compose logs -f --tail 200 "$@" ;;
  version) installed_version ;;
  set-hostname) cmd_set_hostname "$@" ;;
  set-ip) cmd_set_ip "$@" ;;
  mail-volume-cleanup) mail_volume_cleanup force ;;
  restart) cmd_restart "$@" ;;
  reload-edge) cmd_reload_edge ;;
  node-bundle) cmd_node_bundle ;;
  link) cmd_link "$@" ;;
  cleanup)
    exec 9>"$LOCK"
    flock -w 600 9 || die "an update is running; try again later"
    prune_images; df -h "$LIB/registry" /var/lib/docker | awk 'NR == 1 || !seen[$1]++' ;;
  move-layout) log "this server has the ScalPanel names already" ;;
  *) sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
