#!/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 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 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
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_VERSION=""
status() { # state message
  [ -d "$UPDATE_DIR" ] || return 0
  local msg=${2//\\/\\\\}
  msg=${msg//\"/\\\"}
  msg=$(printf '%s' "$msg" | tr '\n\r\t' '   ' | cut -c1-1500)
  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)" > "$UPDATE_DIR/.status.tmp"
  chmod 0644 "$UPDATE_DIR/.status.tmp"
  mv "$UPDATE_DIR/.status.tmp" "$UPDATE_DIR/status.json"
}

# ---------------------------------------------------------------- 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 vPanel $RELEASE_VERSION: $n of $missing files"; fi
  done < "$WORK/registry-missing.txt"
  return 0
}

# Writes /etc/vpanel/release.env and /etc/vpanel/release from a release dir.
activate() { # release dir
  local d=$1
  img() { jq -er --arg n "$1" '.images[$n]' "$d/release.json"; }
  local runtimes=""
  for n in $(jq -r '.images | keys[] | select(startswith("runtime:"))' "$d/release.json"); do
    runtimes="$runtimes,${n#runtime:}=registry:5000/$(img "$n")"
  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"
  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
  mv "$ETC/release.env.new" "$ETC/release.env"
  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
}

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

# ---------------------------------------------------------------- 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
    [ -s "$UPDATE_DIR/request.json" ] || exit 0
    want=$(jq -er '.version' "$UPDATE_DIR/request.json" 2>/dev/null) || { rm -f "$UPDATE_DIR/request.json"; exit 0; }
    [[ "$want" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { rm -f "$UPDATE_DIR/request.json"; exit 0; }
    rm -f "$UPDATE_DIR/request.json"
  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"
  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"
  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' certificate: self-signed until replaced (ADR-0063 §5).
  if [ ! -s "$ETC/tls/panel.crt" ]; then
    openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 825 \
      -subj "/CN=$VPANEL_HOSTNAME" -addext "subjectAltName=DNS:$VPANEL_HOSTNAME,IP:$VPANEL_PUBLIC_IP" \
      -keyout "$ETC/tls/panel.key" -out "$ETC/tls/panel.crt" 2>/dev/null
    chmod 0644 "$ETC/tls/panel.crt"; chmod 0600 "$ETC/tls/panel.key"
  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
    head -c 18 /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 use a self-signed certificate until you install your own in
  /etc/vpanel/tls (panel.crt, panel.key) and run: vpanelctl compose restart panel

  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
}

# ---------------------------------------------------------------- status
cmd_status() {
  echo "vPanel $(installed_version) (channel $CHANNEL, $UPDATE_URL)"
  [ -r "$UPDATE_DIR/status.json" ] && echo "last update: $(cat "$UPDATE_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 "$@" ;;
  status) cmd_status ;;
  compose) compose "$@" ;;
  admin) admin "$@" ;;
  logs) compose logs -f --tail 200 "$@" ;;
  version) installed_version ;;
  *) sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
