#!/usr/bin/env bash
# vpanelctl: install, update and operate an all-in-one vPanel server
# (ADR-0063). Installed as /usr/local/sbin/vpanelctl; runs as root.
#
#   vpanelctl status                 versions and service state
#   vpanelctl update [--yes]         install the latest release of the channel
#   vpanelctl update --from-request  what the panel asked for (systemd path unit)
#   vpanelctl runtime install <id>.. PHP versions from the runtime catalog (php-8.6 ...)
#   vpanelctl runtime list           the catalog and what is installed
#   vpanelctl compose <args>         docker compose for this installation
#   vpanelctl admin <args>           vpanel-admin in the control-plane image
#   vpanelctl logs <service>         follow a service's log
#   vpanelctl set-hostname <name>    change the panel hostname (certificate follows)
#   vpanelctl 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

RELEASE_PUBLIC_KEY="vprk1.QUorqm4dmqc5VKSD6_KfNN9erY0Go0bhP2NcrIYNilA"
UPDATE_URL_DEFAULT="https://vpanel.scb.network"

ETC=/etc/vpanel
LIB=/var/lib/vpanel
OPT=/opt/vpanel
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
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 vpanel.env
  local v=${!1:-}
  [ -z "$v" ] && [ -r "$ETC/vpanel.env" ] && v=$(sed -n "s/^$1=//p" "$ETC/vpanel.env" | tail -1)
  printf '%s' "${v:-$2}"
}
UPDATE_URL=$(setting VPANEL_UPDATE_URL "$UPDATE_URL_DEFAULT")
CHANNEL=$(setting VPANEL_UPDATE_CHANNEL stable)
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).
STATUS_VERSION=""
STATUS_FILE=status.json
status() { # state message
  [ -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
  printf '{"state":"%s","version":"%s","current":"%s","message":"%s","updated_at":"%s"}\n' \
    "$1" "$STATUS_VERSION" "$(installed_version)" "$msg" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$tmp"
  chmod 0644 "$tmp"
  mv -fT "$tmp" "$STATUS_DIR/$STATUS_FILE"
}

# ---------------------------------------------------------------- verification
# The release key is ed25519 ("vprk1." + 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#vprk1.}
  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, VPANEL_ALLOW_HTTP=1)
  local proto="=https"
  [ "$(setting VPANEL_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
compose() {
  docker compose --project-name vpanel --project-directory "$OPT/current" -f "$OPT/current/compose.yaml" \
    --env-file "$ETC/release.env" --env-file "$ETC/vpanel.env" "$@"
}

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

# Runs vpanel-admin with the control plane's configuration.
admin() {
  compose run --rm --no-deps -T migrate vpanel-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"
  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 vPanel $RELEASE_VERSION"
  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.
sync_registry() { # list
  local list=$1 total missing=0 n=0
  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
    printf '%s %s\n' "$sum" "$path"
  done < "$list" > "$WORK/registry-missing.txt"
  missing=$(wc -l < "$WORK/registry-missing.txt")
  log "registry: $missing of $total files to download"
  while read -r sum 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"
    if [ $((n % 20)) -eq 0 ]; then status downloading "downloading ${SYNC_LABEL:-vPanel $RELEASE_VERSION}: $n of $missing files"; fi
  done < "$WORK/registry-missing.txt"
  return 0
}

# Writes /etc/vpanel/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 vpanelctl for vPanel $(json .version "$d/release.json"); do not edit."
    echo "VPANEL_IMAGE_CONTROLPLANE=127.0.0.1:5000/$(img controlplane)"
    echo "VPANEL_IMAGE_WEB=127.0.0.1:5000/$(img web)"
    echo "VPANEL_IMAGE_NODE=127.0.0.1:5000/$(img node)"
    echo "VPANEL_IMAGE_MAIL=127.0.0.1:5000/$(img mail)"
    echo "VPANEL_SESSION_IMAGE=registry:5000/$(img session)"
    echo "VPANEL_RUNTIME_IMAGES=${runtimes#,}"
    echo "VPANEL_RELEASE_PUBLIC_KEY=$RELEASE_PUBLIC_KEY"
  } > "$ETC/release.env.new"
  mv "$ETC/release.env.new" "$ETC/release.env"
}

# Writes /etc/vpanel/release.env and /etc/vpanel/release from a release dir.
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 -m 0755 "$d/bin/vpanelctl" /usr/local/sbin/vpanelctl
  install -m 0644 "$d/systemd/vpanel-update.path" /etc/systemd/system/vpanel-update.path
  install -m 0644 "$d/systemd/vpanel-update.service" /etc/systemd/system/vpanel-update.service
  systemctl daemon-reload 2>/dev/null || true
  # A path unit watches the paths it had when it started.
  systemctl try-restart vpanel-update.path 2>/dev/null || true
}

# The local MariaDB's provisioning account gains what later releases need
# (idempotent): PROCESS and CONNECTION ADMIN for the database processes page
# (ADR-0125).
mariadb_grants() {
  [ -s "$ETC/secrets/mariadb-root" ] || return 0
  compose exec -T mariadb sh -c 'mariadb -uroot -p"$(cat /run/vpanel-db/mariadb-root 2>/dev/null || printf %s "$MARIADB_ROOT_PASSWORD")" -e "GRANT PROCESS, CONNECTION ADMIN ON *.* TO '"'"'vpanel_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"
}

# 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 vpanel_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]?)$ ]]; }
image_ok() { [[ "$1" =~ ^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 vPanel $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 vPanel 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>/run/vpanel-update.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: vpanelctl 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: vpanelctl 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 vpanelctl 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>/run/vpanel-update.lock
  flock -n 9 || { log "another update is running"; exit 0; }
  if [ $from_request = 1 ]; then
    service_from_request
    runtime_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"
  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 "vPanel $cur is installed; $want is not newer"
    [ $from_request = 1 ] && status "done" "vPanel $cur is up to date"
    exit 0
  fi
  if [ $yes = 0 ]; then
    printf 'Update vPanel %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 vPanel $cur to $want"
  download_release "$want"
  status installing "installing vPanel $RELEASE_VERSION"
  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 vpanel -Fc vpanel > "$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
  activate "$RELEASE_DIR"
  mail_upgrades "$RELEASE_DIR"
  mariadb_grants
  compose pull --quiet || die "the new images cannot be pulled from the local registry"
  compose up -d --remove-orphans || true
  if ! wait_healthy 600 api worker webmail-api mail panel node; then
    log "vPanel $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).
    VPANEL_ALLOW_NEWER_SCHEMA=true compose up -d --remove-orphans || true
    die "vPanel $RELEASE_VERSION did not start; $(basename "$prev") was restored (database backup in $LIB/backups)"
  fi
  echo "$RELEASE_VERSION" > "$ETC/version"
  # 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" "vPanel $RELEASE_VERSION is installed"
  log "vPanel $RELEASE_VERSION is installed"
}

# ---------------------------------------------------------------- install
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() {
  : "${VPANEL_HOSTNAME:?}" "${VPANEL_PUBLIC_IP:?}" "${VPANEL_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/vpanel "$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/vpanel

  # This server's settings.
  if [ ! -s "$ETC/vpanel.env" ]; then
    cat > "$ETC/vpanel.env" <<EOF
# vPanel server settings (ADR-0063). Edit, then: vpanelctl compose up -d
VPANEL_HOSTNAME=$VPANEL_HOSTNAME
VPANEL_PUBLIC_IP=$VPANEL_PUBLIC_IP
VPANEL_ADMIN_EMAIL=$VPANEL_ADMIN_EMAIL
VPANEL_MAIL_HOSTNAME=${VPANEL_MAIL_HOSTNAME:-$VPANEL_HOSTNAME}
VPANEL_NAMESERVERS=${VPANEL_NAMESERVERS:-ns1.$VPANEL_HOSTNAME,ns2.$VPANEL_HOSTNAME}
VPANEL_UPDATE_URL=$UPDATE_URL
VPANEL_UPDATE_CHANNEL=$CHANNEL
EOF
    # Installer tests only: a release site over plain HTTP.
    if [ "${VPANEL_ALLOW_HTTP:-0}" = 1 ]; then echo "VPANEL_ALLOW_HTTP=1" >> "$ETC/vpanel.env"; fi
    chmod 0644 "$ETC/vpanel.env"
  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
  printf 'postgres:5432:vpanel:vpanel:%s\n' "$(cat "$ETC/secrets/postgres")" > "$ETC/secrets/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 vpanel-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/vpanel/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 "$VPANEL_HOSTNAME" "$VPANEL_PUBLIC_IP"; fi

  pubkey_pem
  download_release "${VPANEL_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 vpanel-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 vpanel-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 vpanel-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 VPANEL_BOOTSTRAP_EMAIL="$VPANEL_ADMIN_EMAIL" migrate vpanel-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 vpanel-admin dbserver-add main mariadb 3306 3306 vpanel_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/vpanel/secrets/node.bundle"
    fi
    # The bundle is the line starting with vpe1. (logs share stdout).
    compose run --rm -T migrate vpanel-admin node-create node-1 web | grep '^vpe1\.' > "$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 vPanel"
  compose up -d --remove-orphans || die "vPanel did not start; see: vpanelctl compose ps"
  wait_healthy 900 api worker webmail-api mail panel node || die "vPanel did not become healthy; see: vpanelctl status"
  echo "$STATUS_VERSION" > "$ETC/version"
  systemctl enable --now vpanel-update.path >/dev/null 2>&1 || true
  status "done" "vPanel $STATUS_VERSION is installed"
  cat <<EOF

  vPanel $STATUS_VERSION is installed.

    Admin panel     https://$VPANEL_HOSTNAME:2087   (or https://$VPANEL_PUBLIC_IP:2087)
    Customer panel  https://$VPANEL_HOSTNAME:2083
    Webmail         https://$VPANEL_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 $VPANEL_HOSTNAME
  points at this server; until then they use a self-signed one.
  To change the hostname later: vpanelctl set-hostname <name>

  DNS: point $VPANEL_HOSTNAME (A) to $VPANEL_PUBLIC_IP; for hosted DNS,
  create glue records for the nameservers in /etc/vpanel/vpanel.env.
  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: vpanelctl set-hostname <panel.example.com>"
  fi
  [ -s "$ETC/vpanel.env" ] || die "vPanel is not installed"
  old=$(setting VPANEL_HOSTNAME "")
  ip=$(setting VPANEL_PUBLIC_IP "")
  if [ "$new" = "$old" ]; then
    log "the hostname is already $new"
    return 0
  fi
  sed -i "s/^VPANEL_HOSTNAME=.*/VPANEL_HOSTNAME=$new/" "$ETC/vpanel.env"
  # The mail hostname followed the panel's unless it was set on its own.
  if grep -qxF "VPANEL_MAIL_HOSTNAME=$old" "$ETC/vpanel.env"; then
    sed -i "s/^VPANEL_MAIL_HOSTNAME=.*/VPANEL_MAIL_HOSTNAME=$new/" "$ETC/vpanel.env"
  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
}

# ---------------------------------------------------------------- status
cmd_status() {
  echo "vPanel $(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}}'
}

[ "$(id -u)" = 0 ] || { echo "vpanelctl must run as root" >&2; exit 1; }
cmd=${1:-status}; shift || true
case "$cmd" in
  install) cmd_install "$@" ;;
  update) cmd_update "$@" ;;
  runtime) cmd_runtime "$@" ;;
  status) cmd_status ;;
  compose) compose "$@" ;;
  admin) admin "$@" ;;
  logs) compose logs -f --tail 200 "$@" ;;
  version) installed_version ;;
  set-hostname) cmd_set_hostname "$@" ;;
  *) sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
