#!/usr/bin/env bash
# ======================================================================================================================
#  API Maker v4 installer : API Maker (api_maker_be_rust, one program written in Rust) on an Ubuntu server.
#
#    curl -fsSL https://apimaker.dev/v4/install.sh > install.sh && bash install.sh --version=latest --license_key=YOUR_KEY
#
#  Installs and starts : Docker (the sandboxes of the code of the accounts), MongoDB and Redis in Docker, the Oracle
#  Instant Client, API Maker run by systemd as the service api_maker_be (it serves the APIs, the web sockets and the
#  admin panel), and in front of it Caddy, or API Maker's built-in web server (--proxy=builtin : no other program, the
#  fastest way), with HTTPS. Nothing of Node.js is installed : the server is one program.
#
#  Run it again to upgrade (--version=<x.y.z> or latest), to change a setting, or to repair an installation : what it
#  wrote before is backed up and its answers are offered again. A version which does not start is rolled back.
#
#  Flags (every question has a flag, so the installer runs without questions too) :
#    --default                  take the default of every question that has one
#    --version=<x.y.z|latest>   the version of API Maker (latest)
#    --license_key=<key>        the license key of the account (--extLicenseKey=<key> too)
#    --package=<file or URL>    a release archive to install instead of downloading one (.tar.gz or the .tgz of npm)
#    --primary | --secondary    the first server of an installation, or one more server attached to it
#    --ip=<address>             the public IPv4 address of this server
#    --proxy=caddy|builtin|none what answers on ports 80 and 443 : Caddy (caddy), API Maker's built-in web server (builtin),
#                               or nothing (none : the ports belong to another server, Nginx, Apache…). --caddy=yes|no too
#    --ssl=yes|no|ip            HTTPS with certificates of Let's Encrypt (no), with --api_domain, --ws_domain, --panel_domain;
#                               ip : HTTPS on the IP address of the server, without domains (--proxy=builtin)
#    --primary_ip=<address>     a secondary server with --proxy=builtin : the address the primary server connects from
#    --qa_uat_prod=yes|no       a QA, UAT or PROD environment of a project (no)
#    --mongoVersion=<x.y.z>     the image of MongoDB (8.0.10)
#    --skip_dns_check           take domains which do not point to this server yet
#    --help
#
#  Secrets and connection strings are not flags (a command line is seen by every process of the server) : the variables
#  AM_PASS_COMMUNICATION, AM_PASS_JWT, AM_PASS_DB_ENCRYPT_DECRYPT, AM_MONGO_CONNECTION, AM_REDIS_INTERNAL,
#  AM_REDIS_EXTERNAL and AM_SERVER_NAME answer those questions (a secondary server needs the ones of its primary server).
#
#  Logs of the installer : ~/logs/install/. Settings of API Maker : ~/config/.env.
# ======================================================================================================================
set -Eeuo pipefail
umask 022

# ---------------------------------------------------------------------------------------------------- constants

readonly AM_MAJOR=4
readonly DEFAULT_API_PORT=38246      # the APIs and the web sockets, on one port
readonly DEFAULT_PANEL_PORT=4626     # the admin panel, served by API Maker itself
readonly DEFAULT_MONGO_PORT=38248
readonly DEFAULT_MONGO_USER=api_maker_user
readonly DEFAULT_REDIS_PORT=7479
readonly DEFAULT_MONGO_VERSION=8.0.10
readonly CADDY_API_PORT=8080         # without SSL : the APIs behind Caddy
readonly CADDY_WS_PORT=8081          # without SSL : the web sockets behind Caddy (the same port of API Maker)
readonly MONGODB_CONTAINER=mongodb_api_maker
readonly REDIS_CONTAINER=redis_api_maker
readonly SERVICE=api_maker_be
readonly OLD_PANEL_SERVICE=api_maker_fe  # the admin panel server of the Node.js edition : API Maker serves it now
readonly LOGROTATE_SERVICE=api_maker_logrotate
readonly SYSTEMD_DIR=/etc/systemd/system
readonly NPM_REGISTRY="${AM_NPM_REGISTRY:-https://registry.npmjs.org}"
readonly NPM_SCOPE="${AM_NPM_SCOPE:-@sava-info-systems}"
readonly CADDY_VERSION=2.10.2        # used when the latest version can not be read
readonly ORACLE_X64_URL="https://images.apimaker.dev/prod/am-cloud/binaries/oracle-clients/21.8.0/instantclient-basic-linuxx64.zip"
readonly ORACLE_ARM64_URL="https://download.oracle.com/otn_software/linux/instantclient/instantclient-basic-linux-arm64.zip"
readonly LICENSE_CORE_URL="https://sava.be.apimaker.dev/api/custom-api/admin/am-cloud/license/get-license-core"
readonly LICENSE_RESET_URL="https://sava.be.apimaker.dev/api/custom-api/admin/am-cloud/license/reset-mac-address-of-license"
readonly KEEP_RELEASES=3

HOME_DIR="${HOME:-/root}"
APP_ROOT="$HOME_DIR/projects/api_maker"         # uploads, license.txt : what stays from one version to the next
RELEASES="$APP_ROOT/releases"                   # one folder per version
CURRENT="$APP_ROOT/current"                     # the version that runs
CONFIG="$HOME_DIR/config"
SERVICE_FOLDER="$CONFIG/api_maker"
ENV_FILE="$CONFIG/.env"
CADDYFILE="$CONFIG/Caddyfile"
# API Maker's built-in web server : the folder of its settings (edge next to the .env, where API Maker looks for it).
EDGE_DIR="$CONFIG/edge"
EDGE_FILE="$EDGE_DIR/edge.json"
EDGE_STATUS="$EDGE_DIR/edge.status.json"
readonly MODULES_FILE=/etc/modules-load.d/api-maker-tls.conf
LOGS="$HOME_DIR/logs"
LOG_FILE="$LOGS/api_maker_be.txt"
DOCKER_DATA="$HOME_DIR/docker-data"
OLD_APP_ROOT="$HOME_DIR/projects/sava_api_maker" # the Node.js edition (v1 to v3)

# ---------------------------------------------------------------------------------------------------- output

if [ -t 1 ]; then
    C_RED=$'\e[31m'; C_GREEN=$'\e[32m'; C_YELLOW=$'\e[33m'; C_CYAN=$'\e[36m'; C_BOLD=$'\e[1m'; C_DIM=$'\e[2m'; C_OFF=$'\e[0m'
else
    C_RED=''; C_GREEN=''; C_YELLOW=''; C_CYAN=''; C_BOLD=''; C_DIM=''; C_OFF=''
fi
INSTALL_LOG=/dev/null

ok() { printf '✅  %s\n' "$*"; }
info() { printf '🔶  %s\n' "$*"; }
note() { printf '👉  %s\n' "$*"; }
warn() { printf '%s⚠️   %s%s\n' "$C_YELLOW" "$*" "$C_OFF"; }
fail() {
    printf '\n%s❌  %s%s\n' "$C_RED" "$*" "$C_OFF" >&2
    [ "$INSTALL_LOG" != /dev/null ] && printf '    The log of the installer : %s\n' "$INSTALL_LOG" >&2
    start_again_after_failure
    exit 1
}
# API Maker was stopped for the installation and nothing of it changed yet : it runs again when the installation stops.
WAS_RUNNING=0
start_again_after_failure() {
    # The built-in web server this run turned off for another web server comes back as it was.
    if [ "${EDGE_TURNED_OFF:-0}" = 1 ] && [ -n "${EDGE_BACKUP:-}" ] && [ -f "${EDGE_BACKUP:-}" ]; then
        EDGE_TURNED_OFF=0
        systemctl disable --quiet --now caddy >/dev/null 2>&1 || true
        cp -p "$EDGE_BACKUP" "$EDGE_FILE" && printf '    API Maker'"'"'s built-in web server, as it was, is on again.\n' >&2 || true
    fi
    if [ "$WAS_RUNNING" = 1 ]; then
        WAS_RUNNING=0
        systemctl start api_maker_be >/dev/null 2>&1 && printf '    API Maker, as it was, runs again.\n' >&2 || true
    fi
}
section() { printf '\n%s———— %s ————%s\n' "$C_CYAN" "$*" "$C_OFF"; }
on_error() {
    local status=$? line=$1
    printf '\n%s❌  The installer stopped at line %s (exit %s).%s\n' "$C_RED" "$line" "$status" "$C_OFF" >&2
    [ "$INSTALL_LOG" != /dev/null ] && printf '    The log of the installer : %s\n' "$INSTALL_LOG" >&2
    start_again_after_failure
    exit "$status"
}
trap 'on_error $LINENO' ERR

# Runs a command, its output into the log of the installer : "⏳ what" while it runs, then "✅ what". On failure the end
# of its output is shown and the installer stops.
run() {
    local what=$1
    shift
    if [ -t 1 ]; then printf '⏳  %s…' "$what"; else printf '⏳  %s…\n' "$what"; fi
    printf '\n==== %s : %s\n' "$(date '+%F %T')" "$what" >>"$INSTALL_LOG"
    local status=0
    "$@" >>"$INSTALL_LOG" 2>&1 || status=$?
    if [ -t 1 ]; then printf '\r\e[K'; fi
    if [ "$status" -ne 0 ]; then
        printf '%s❌  %s failed (exit %s). The end of its output :%s\n' "$C_RED" "$what" "$status" "$C_OFF" >&2
        tail -n 30 "$INSTALL_LOG" | sed 's/^/    /' >&2
        fail "$what failed."
    fi
    ok "$what"
}

# A command whose failure is an answer, not an error : its output, empty when it failed.
try() { "$@" 2>/dev/null || true; }

# ---------------------------------------------------------------------------------------------------- arguments

ARG_DEFAULT=0
ARG_VERSION=latest
ARG_LICENSE_KEY=''
ARG_PACKAGE=''
ARG_KIND=''
ARG_IP=''
ARG_CADDY=''
ARG_PROXY=''
ARG_PRIMARY_IP=''
ARG_SSL=''
ARG_API_DOMAIN=''
ARG_WS_DOMAIN=''
ARG_PANEL_DOMAIN=''
ARG_QA=''
ARG_MONGO_VERSION=$DEFAULT_MONGO_VERSION
ARG_SKIP_DNS=0

# The header of this file, from its first line of = to the next one.
usage() { awk 'NR > 2 && /^# =+$/ { exit } NR > 2 { print }' "$0" | sed -E 's/^#( {1,2})?//'; }

for argument in "$@"; do
    case "$argument" in
        --default) ARG_DEFAULT=1 ;;
        --version=*) ARG_VERSION="${argument#*=}" ;;
        --license_key=* | --extLicenseKey=*) ARG_LICENSE_KEY="${argument#*=}" ;;
        --license_key | --extLicenseKey) fail "Please give the license key as --license_key=YOUR_KEY" ;;
        --package=*) ARG_PACKAGE="${argument#*=}" ;;
        --primary) ARG_KIND=PRIMARY ;;
        --secondary) ARG_KIND=SECONDARY ;;
        --ip=*) ARG_IP="${argument#*=}" ;;
        --caddy=*) ARG_CADDY="${argument#*=}" ;;
        --proxy=*) ARG_PROXY="${argument#*=}" ;;
        --primary_ip=*) ARG_PRIMARY_IP="${argument#*=}" ;;
        --ssl=*) ARG_SSL="${argument#*=}" ;;
        --api_domain=*) ARG_API_DOMAIN="${argument#*=}" ;;
        --ws_domain=*) ARG_WS_DOMAIN="${argument#*=}" ;;
        --panel_domain=*) ARG_PANEL_DOMAIN="${argument#*=}" ;;
        --qa_uat_prod=*) ARG_QA="${argument#*=}" ;;
        --mongoVersion=*) ARG_MONGO_VERSION="${argument#*=}" ;;
        --skip_dns_check) ARG_SKIP_DNS=1 ;;
        -h | --help) usage; exit 0 ;;
        *) fail "Unknown argument : $argument (bash install.sh --help lists them)" ;;
    esac
done
ARG_LICENSE_KEY="$(printf '%s' "$ARG_LICENSE_KEY" | tr -d '[:space:]')"
# --caddy=yes|no says --proxy=caddy|none.
if [ -z "$ARG_PROXY" ] && [ -n "$ARG_CADDY" ]; then
    case "$ARG_CADDY" in
        yes | y | true | 1) ARG_PROXY=caddy ;;
        no | n | false | 0) ARG_PROXY=none ;;
        *) fail "--caddy is yes or no, not '$ARG_CADDY'" ;;
    esac
fi
case "$ARG_PROXY" in
    '' | caddy | builtin | none) ;;
    *) fail "--proxy is caddy, builtin or none, not '$ARG_PROXY'" ;;
esac
if [ "$ARG_SSL" = ip ] && [ "$ARG_PROXY" != builtin ]; then fail "--ssl=ip (HTTPS on the IP address) needs --proxy=builtin"; fi
case "$ARG_VERSION" in
    latest | [0-9]*.[0-9]*.[0-9]*) ;;
    *) fail "--version is latest or a version like 4.0.0, not '$ARG_VERSION'" ;;
esac

# ---------------------------------------------------------------------------------------------------- questions

# Questions are read from the terminal, so the installer can be piped into bash too. Without a terminal every question
# takes its default (or the flag which answers it).
CAN_ASK=0
if [ -r /dev/tty ] && [ -w /dev/tty ] && { : </dev/tty; } 2>/dev/null; then CAN_ASK=1; fi

# ask <variable> <question> <default> [<check>] : the answer, the default when the answer is empty. <check> prints why
# an answer is refused and fails.
ask() {
    local __ask_var=$1 __ask_question=$2 __ask_default=$3 __ask_check=${4:-} __ask_answer __ask_why
    while true; do
        if [ "$CAN_ASK" = 1 ]; then
            printf '%s?%s %s %s[%s]%s : ' "$C_GREEN" "$C_OFF" "$__ask_question" "$C_DIM" "$__ask_default" "$C_OFF" >/dev/tty
            IFS= read -r __ask_answer </dev/tty || __ask_answer=''
            __ask_answer="${__ask_answer:-$__ask_default}"
        else
            __ask_answer=$__ask_default
        fi
        __ask_answer="$(printf '%s' "$__ask_answer" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
        if [ -n "$__ask_check" ] && ! __ask_why="$($__ask_check "$__ask_answer")"; then
            [ "$CAN_ASK" = 1 ] || fail "$__ask_question : $__ask_why"
            printf '   %s%s%s\n' "$C_YELLOW" "$__ask_why" "$C_OFF" >/dev/tty
            continue
        fi
        printf -v "$__ask_var" '%s' "$__ask_answer"
        return 0
    done
}

# ask_or_default : the same, but the default is taken without asking with --default.
ask_or_default() {
    local __aod_var=$1 __aod_question=$2 __aod_default=$3 __aod_check=${4:-} __aod_why
    if [ "$ARG_DEFAULT" = 1 ]; then
        if [ -n "$__aod_check" ] && ! __aod_why="$($__aod_check "$__aod_default")"; then fail "$__aod_question : $__aod_why"; fi
        printf -v "$__aod_var" '%s' "$__aod_default"
        return 0
    fi
    ask "$@"
}

# ask_given <variable> <question> <default> <check> <given> : the value a variable of the environment gives, checked, or
# the question.
ask_given() {
    local __ag_var=$1 __ag_question=$2 __ag_default=$3 __ag_check=$4 __ag_given=${5:-} __ag_why
    if [ -n "$__ag_given" ]; then
        if [ -n "$__ag_check" ] && ! __ag_why="$($__ag_check "$__ag_given")"; then fail "$__ag_question : $__ag_why"; fi
        printf -v "$__ag_var" '%s' "$__ag_given"
        return 0
    fi
    ask "$__ag_var" "$__ag_question" "$__ag_default" "$__ag_check"
}

# ask_yes_no <variable> <question> <default yes|no> [<flag value>] : yes or no.
ask_yes_no() {
    local __yn_var=$1 __yn_question=$2 __yn_default=$3 __yn_given=${4:-} __yn_answer
    if [ -n "$__yn_given" ]; then
        case "$__yn_given" in
            yes | y | true | 1) printf -v "$__yn_var" yes ;;
            no | n | false | 0) printf -v "$__yn_var" no ;;
            *) fail "$__yn_question : yes or no, not '$__yn_given'" ;;
        esac
        return 0
    fi
    ask __yn_answer "$__yn_question (yes/no)" "$__yn_default" is_yes_no
    case "$__yn_answer" in yes | y | Y | YES | Yes | true) printf -v "$__yn_var" yes ;; *) printf -v "$__yn_var" no ;; esac
}

is_yes_no() { case "$1" in yes | y | Y | YES | Yes | no | n | N | NO | No | true | false) return 0 ;; *) echo "yes or no"; return 1 ;; esac; }
is_ipv4() {
    if [[ "$1" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]]; then
        local part
        for part in "${BASH_REMATCH[@]:1}"; do [ "$part" -le 255 ] || { echo "Please give a valid IPv4 address."; return 1; }; done
        return 0
    fi
    echo "Please give a valid IPv4 address."
    return 1
}
is_name() { [[ "$1" =~ ^[A-Za-z0-9_.-]{2,64}$ ]] || { echo "2 to 64 letters, digits, '.', '_' or '-'."; return 1; }; }
# A secret of an earlier installation is taken as it is, whatever it is made of : the data was encrypted with it.
KEPT_SECRET=''
is_secret_20() { [ -n "$KEPT_SECRET" ] && [ "$1" = "$KEPT_SECRET" ] && return 0; is_secret "$1" 20 "at least 20"; }
is_secret_32() { [ -n "$KEPT_SECRET" ] && [ "$1" = "$KEPT_SECRET" ] && return 0; is_secret "$1" 32 "exactly 32"; }
# ask_secret <variable> <question> <old value> <length 20|32> <always ask> [<given>] [<length of a new one>] : the old
# value, else a new random one. An answer is checked against <length> (at least 20, or exactly 32), and a new one has
# <length> characters unless <length of a new one> says otherwise.
ask_secret() {
    local __as_var=$1 __as_question=$2 __as_kept=$3 __as_length=$4 __as_always=$5 __as_default=$3 __as_given=${6:-} __as_new=${7:-$4} __as_why
    [ -n "$__as_default" ] || __as_default="$(random_text "$__as_new")"
    KEPT_SECRET=$__as_kept
    if [ -n "$__as_given" ]; then
        __as_why="$("is_secret_$__as_length" "$__as_given")" || fail "$__as_question : $__as_why"
        printf -v "$__as_var" '%s' "$__as_given"
        KEPT_SECRET=''
        return 0
    fi
    if [ "$__as_always" = 1 ]; then
        ask "$__as_var" "$__as_question" "$__as_default" "is_secret_$__as_length"
    else
        ask_or_default "$__as_var" "$__as_question" "$__as_default" "is_secret_$__as_length"
    fi
    KEPT_SECRET=''
}
is_secret() {
    local value=$1 length=$2 words=$3
    [[ "$value" =~ ^[A-Za-z0-9_]+$ ]] || { echo "Only a-z, A-Z, 0-9 and _ : other characters break the automation of the setup."; return 1; }
    if [ "$words" = "exactly 32" ]; then [ "${#value}" -eq 32 ] || { echo "Exactly 32 characters."; return 1; }; fi
    [ "${#value}" -ge "$length" ] || { echo "At least $length characters."; return 1; }
}
is_password() {
    [[ "$1" =~ ^[A-Za-z0-9_]{4,32}$ ]] || { echo "4 to 32 characters among a-z, A-Z, 0-9 and _."; return 1; }
}
is_user_name() { [[ "$1" =~ ^[A-Za-z0-9_]{4,32}$ ]] || { echo "4 to 32 characters among a-z, A-Z, 0-9 and _."; return 1; }; }
is_domain() {
    local domain=$1
    if is_ipv4 "$domain" >/dev/null; then echo "A domain name, not an IP address."; return 1; fi
    case "$domain" in *://* | */*) echo "The domain alone, without http(s):// or a path. ex : api.example.com"; return 1 ;; esac
    [[ "$domain" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$ ]] || { echo "Not a domain name. ex : api.example.com"; return 1; }
    [ "$ARG_SKIP_DNS" = 1 ] && return 0
    if ! getent ahostsv4 "$domain" 2>/dev/null | awk '{print $1}' | grep -qx "$SERVER_IP"; then
        echo "$domain does not point to $SERVER_IP yet : Let's Encrypt checks it. Point its A record here, or give --skip_dns_check."
        return 1
    fi
}
port_number() { [[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -ge 2000 ] && [ "$1" -le 60000 ] || { echo "A port between 2000 and 60000."; return 1; }; }
port_is_free() { [ -z "$(ss -ltnH "( sport = :$1 )" 2>/dev/null)" ]; }
random_text() { LC_ALL=C tr -dc 'a-zA-Z0-9_' </dev/urandom 2>/dev/null | head -c "$1" || true; }

# ---------------------------------------------------------------------------------------------------- the server

ARCH=''
UBUNTU=''
SYSTEMD_VERSION=0
IN_CONTAINER=0

check_server() {
    section "This server"
    [ "$(id -u)" = 0 ] || fail "Please run the installer as root : sudo -i, then bash install.sh …"
    ok "Root user"
    [ -r /etc/os-release ] || fail "This is no Ubuntu server (no /etc/os-release)."
    local os_id os_name
    # In a shell of its own : /etc/os-release sets VERSION, NAME… which are no business of the installer.
    # shellcheck disable=SC1091
    os_id="$(. /etc/os-release && echo "${ID:-}")"
    # shellcheck disable=SC1091
    os_name="$(. /etc/os-release && echo "${PRETTY_NAME:-unknown}")"
    # shellcheck disable=SC1091
    UBUNTU="$(. /etc/os-release && echo "${VERSION_ID:-}")"
    [ "$os_id" = ubuntu ] || fail "The operating system is $os_name : API Maker installs on Ubuntu 22.04, 24.04 or 26.04."
    case "${UBUNTU%%.*}" in
        22 | 24 | 26) ok "Ubuntu $UBUNTU" ;;
        *) warn "Ubuntu $UBUNTU is not verified (22.04, 24.04 and 26.04 are) : the installation goes on." ;;
    esac
    case "$(uname -m)" in
        x86_64 | amd64) ARCH=x64 ;;
        aarch64 | arm64) ARCH=arm64 ;;
        *) fail "The processor is $(uname -m) : API Maker runs on x86-64 and ARM64." ;;
    esac
    ok "Processor : $(uname -m)"
    local glibc
    glibc="$(ldd --version 2>/dev/null | head -1 | grep -oE '[0-9]+\.[0-9]+$' || true)"
    if [ -n "$glibc" ]; then
        if [ "$(printf '%s\n2.35\n' "$glibc" | sort -V | head -1)" != 2.35 ]; then
            fail "glibc $glibc : API Maker needs glibc 2.35 or newer (Ubuntu 22.04 or newer)."
        fi
        ok "glibc $glibc"
    fi
    [ -d /run/systemd/system ] || fail "systemd is not running on this server : it is what runs API Maker."
    SYSTEMD_VERSION="$(systemctl --version 2>/dev/null | head -1 | grep -oE '[0-9]+' | head -1 || echo 0)"
    ok "systemd $SYSTEMD_VERSION"
    if [ "$(try systemd-detect-virt --container)" != "" ] && [ "$(try systemd-detect-virt --container)" != none ]; then IN_CONTAINER=1; fi
    local size
    size="$(df -Pk / | awk 'NR == 2 { printf "%d", $2 / 1024 / 1024 }')"
    if [ "${size:-0}" -ge 20 ]; then ok "Disk : ${size} GB"; else warn "Disk : ${size} GB. 20 GB or more is recommended (MongoDB, the images of the sandboxes)."; fi
    if [ "$ARCH" = x64 ] && ! grep -qiw avx /proc/cpuinfo; then
        warn "The processor has no AVX : MongoDB 5 and newer need it. Give --mongoVersion=4.4.29 or a MongoDB of your own."
    fi
}

install_base_packages() {
    export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
    run "apt update" apt-get -o DPkg::Lock::Timeout=600 update -q
    local wanted=() package
    for package in curl ca-certificates jq tar gzip unzip openssl logrotate iproute2 procps file; do
        dpkg -s "$package" >/dev/null 2>&1 || wanted+=("$package")
    done
    if [ "${#wanted[@]}" -gt 0 ]; then
        run "Installing ${wanted[*]}" apt-get -o DPkg::Lock::Timeout=600 install -y -q --no-install-recommends "${wanted[@]}"
    fi
}

# ---------------------------------------------------------------------------------------------------- what is there

declare -A OLD_ENV=()
OLD_EDITION=0

# The settings of an earlier installation (dotenv : KEY=value, "value" or 'value', comments after #).
load_old_env() {
    [ -f "$ENV_FILE" ] || return 0
    local line key value
    while IFS= read -r line || [ -n "$line" ]; do
        line="${line#"${line%%[![:space:]]*}"}"
        line="${line#export }"
        [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
        key="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"
        if [[ "$value" =~ ^\"([^\"]*)\" ]] || [[ "$value" =~ ^\'([^\']*)\' ]]; then
            value="${BASH_REMATCH[1]}"
        else
            value="${value%%[[:space:]]#*}"
            value="${value%"${value##*[![:space:]]}"}"
        fi
        OLD_ENV[$key]="$value"
    done <"$ENV_FILE"
    info "Using the settings of the earlier installation : $ENV_FILE"
}

old() { printf '%s' "${OLD_ENV[$1]:-}"; }

detect_earlier_edition() {
    if [ -f "$OLD_APP_ROOT/main.js" ] || grep -qs 'main.js' "$SYSTEMD_DIR/$SERVICE.service"; then
        OLD_EDITION=1
        info "API Maker of the Node.js edition (v1 to v3) is installed here : v4 takes its place. Its data (MongoDB, Redis, uploaded files, license) stays, its folder $OLD_APP_ROOT is left as it is."
    fi
}

# PM2 ran API Maker on servers installed before systemd did. v4 is no program of Node.js : PM2 can not run it. API Maker
# is taken out of PM2 (whatever else PM2 runs stays), and PM2 stops starting at boot when nothing is left to it.
leave_pm2() {
    local pm2
    pm2="$(try command -v pm2)"
    [ -z "$pm2" ] && [ -x "$HOME_DIR/.volta/bin/pm2" ] && pm2="$HOME_DIR/.volta/bin/pm2"
    [ -n "$pm2" ] || return 0
    local names
    names="$(try "$pm2" jlist | jq -r '.[].name' 2>/dev/null || true)"
    local saved=0
    grep -qs '"name": *"api_maker_\(be\|fe\)"' "$HOME_DIR/.pm2/dump.pm2" && saved=1
    if ! grep -qxE 'api_maker_(be|fe)' <<<"$names" && [ "$saved" = 0 ]; then return 0; fi
    try "$pm2" delete api_maker_be >/dev/null
    try "$pm2" delete api_maker_fe >/dev/null
    try "$pm2" save --force >/dev/null
    local left
    left="$(try "$pm2" jlist | jq -r '.[].name' 2>/dev/null | grep -c . || true)"
    if [ "${left:-0}" = 0 ]; then
        try "$pm2" kill >/dev/null
        local unit
        for unit in $(systemctl list-unit-files --no-legend 'pm2-*.service' 2>/dev/null | awk '{print $1}'); do
            try systemctl disable --quiet --now "$unit"
        done
    fi
    ok "API Maker taken out of PM2 : systemd runs it from now on."
}

stop_api_maker() {
    systemctl is-active --quiet "$SERVICE" 2>/dev/null && WAS_RUNNING=1
    try systemctl stop "$SERVICE"
    try systemctl stop "$OLD_PANEL_SERVICE"
}

# ---------------------------------------------------------------------------------------------------- answers

KIND=PRIMARY
SERVER_IP=''
PROXY=caddy        # what answers on ports 80 and 443 : caddy, builtin (API Maker's built-in web server) or none
INSTALL_CADDY=yes  # PROXY=caddy
INSTALL_SSL=no     # HTTPS with domains
HTTPS_ON_IP=no     # PROXY=builtin : HTTPS on the IP address of the server
PRIMARY_IP=''      # PROXY=builtin on a secondary server : the address of its primary server (its PROXY protocol)
IS_QA=no
API_DOMAIN=''
WS_DOMAIN=''
PANEL_DOMAIN=''
SERVER_NAME=primary
INSTALL_MONGO=yes
INSTALL_REDIS=yes
MONGO_PORT=$DEFAULT_MONGO_PORT
MONGO_USER=$DEFAULT_MONGO_USER
MONGO_PASSWORD=''
REDIS_PORT=$DEFAULT_REDIS_PORT
REDIS_PASSWORD=''
API_PORT=$DEFAULT_API_PORT
PANEL_PORT=$DEFAULT_PANEL_PORT
PASS_COMMUNICATION=''
PASS_JWT=''
PASS_DB=''
MONGO_CONNECTION=''
REDIS_INTERNAL=''
REDIS_EXTERNAL=''
SWAP_MB=0

ask_kind() {
    if [ -n "$ARG_KIND" ]; then KIND=$ARG_KIND; return 0; fi
    local answer
    ask answer "Is this a primary [P] or a secondary [S] server" P is_kind
    case "$answer" in S | s) KIND=SECONDARY ;; *) KIND=PRIMARY ;; esac
}
is_kind() { case "$1" in P | p | S | s) return 0 ;; *) echo "P = primary, S = secondary"; return 1 ;; esac; }

ask_ip() {
    if [ -n "$ARG_IP" ]; then
        is_ipv4 "$ARG_IP" >/dev/null || fail "--ip : $(is_ipv4 "$ARG_IP")"
        SERVER_IP=$ARG_IP
        return 0
    fi
    local found=''
    # The address an earlier installation confirmed : BE_HOST_PORT is http://<ip>:<port> without SSL, a domain with it.
    found="$(old BE_HOST_PORT | sed -nE 's#^https?://([^/:]+).*#\1#p')"
    if ! is_ipv4 "$found" >/dev/null; then
        found="$(curl -fsS --max-time 6 https://ipinfo.io/ip 2>/dev/null || curl -fsS --max-time 6 https://api.ipify.org 2>/dev/null || true)"
        is_ipv4 "$found" >/dev/null || found="$(hostname -I 2>/dev/null | awk '{print $1}')"
    fi
    # Not taken without a word : some providers answer with the address of a gateway.
    ask SERVER_IP "The public IP address of this server" "$found" is_ipv4
}

# What answered on ports 80 and 443 after the last run : builtin (the built-in web server, on), caddy (its service), none,
# or nothing for a fresh server.
current_proxy() {
    if [ -f "$EDGE_FILE" ] && [ "$(try jq -r '.enabled // false' "$EDGE_FILE")" = true ]; then echo builtin; return 0; fi
    if systemctl is-enabled --quiet caddy 2>/dev/null; then echo caddy; return 0; fi
    if [ -f "$ENV_FILE" ]; then echo none; fi
}

ask_proxy() {
    if [ -n "$ARG_PROXY" ]; then
        PROXY=$ARG_PROXY
    else
        printf '%s   caddy   :%s Caddy in front of API Maker, with or without SSL.\n' "$C_DIM" "$C_OFF"
        printf '%s   builtin :%s API Maker serves HTTPS itself : no other program in front of it, the fastest way.\n' "$C_DIM" "$C_OFF"
        printf '%s   none    :%s ports 80 and 443 belong to another server here (Nginx, Apache…) : API Maker answers on its own ports.\n' "$C_DIM" "$C_OFF"
        local current
        current="$(current_proxy)"
        ask PROXY "Which web server answers in front of API Maker : caddy, builtin or none" "${current:-caddy}" is_proxy
    fi
    INSTALL_CADDY=no
    [ "$PROXY" = caddy ] && INSTALL_CADDY=yes
    case "$PROXY" in
        caddy) ask_yes_no INSTALL_SSL "Do you want to install SSL (HTTPS with Let's Encrypt)" no "$ARG_SSL" ;;
        builtin)
            if [ "$KIND" = SECONDARY ]; then
                # The primary server shares the connections with this one : API Maker here takes its PROXY protocol.
                local old_primary
                old_primary="$(try jq -r '.acceptProxyProtocolFrom[0] // ""' "$EDGE_FILE")"
                ask_given PRIMARY_IP "The IP address the primary server connects from (its private address on a private network)" "$old_primary" is_ipv4 "$ARG_PRIMARY_IP"
                ask_edge_takeover
                return 0
            fi
            local https
            case "$ARG_SSL" in
                yes | y | true | 1) https=domains ;;
                no | n | false | 0) https=no ;;
                ip) https=ip ;;
                '')
                    printf '%s   domains :%s HTTPS with your domains (Let'"'"'s Encrypt, certificates of %s days).\n' "$C_DIM" "$C_OFF" "$(domain_certificate_days)"
                    printf '%s   ip      :%s HTTPS on the IP address of this server (certificates of 6 days, renewed by API Maker).\n' "$C_DIM" "$C_OFF"
                    printf '%s   no      :%s plain HTTP on the address of the server.\n' "$C_DIM" "$C_OFF"
                    ask https "HTTPS : domains, ip or no" "$(old_https)" is_https_choice
                    ;;
                *) fail "--ssl is yes, no or ip, not '$ARG_SSL'" ;;
            esac
            INSTALL_SSL=no; HTTPS_ON_IP=no
            [ "$https" = domains ] && INSTALL_SSL=yes
            [ "$https" = ip ] && HTTPS_ON_IP=yes
            ;;
    esac
    ask_edge_takeover
    return 0
}

# Settings of the built-in web server the admin panel changed (its Web Server page) : replaced only when the answer is
# yes (they are kept in backups/ then).
EDGE_KEEP=no
ask_edge_takeover() {
    [ "$PROXY" = builtin ] && [ -f "$EDGE_FILE" ] || return 0
    local managed replace
    managed="$(try jq -r '.managedBy // ""' "$EDGE_FILE")"
    case "$managed" in installer | '') return 0 ;; esac
    ask_yes_no replace "The settings of the built-in web server were changed in the admin panel ($managed) : replace them with the installer's" no "$([ "$ARG_DEFAULT" = 1 ] && echo no)"
    [ "$replace" = yes ] || EDGE_KEEP=yes
}
is_proxy() { case "$1" in caddy | builtin | none) return 0 ;; *) echo "caddy, builtin or none"; return 1 ;; esac; }
is_https_choice() { case "$1" in domains | ip | no) return 0 ;; *) echo "domains, ip or no"; return 1 ;; esac; }
# The HTTPS of an earlier installation : its address (BE_HOST_PORT) says it.
old_https() {
    case "$(old BE_HOST_PORT)" in
        https://[0-9]*.[0-9]*.[0-9]*.[0-9]*) echo ip ;;
        https://*) echo domains ;;
        *) echo no ;;
    esac
}
# How many days a certificate of Let's Encrypt lasts for a domain on a day (YYYYMMDD, today by default) : 90, then 64
# from 10 February 2027 and 45 from 16 February 2028, as Let's Encrypt announced (letsencrypt.org/2025/12/02/from-90-to-45).
domain_certificate_days() {
    local day=${1:-$(date -u +%Y%m%d)}
    if [ "$day" -lt 20270210 ]; then echo 90
    elif [ "$day" -lt 20280216 ]; then echo 64
    else echo 45; fi
}

ask_domains() {
    [ "$INSTALL_SSL" = yes ] || return 0
    note "Domains without http(s)://, each pointing to $SERVER_IP. ex : api.example.com"
    if [ -n "$ARG_API_DOMAIN" ]; then
        is_domain "$ARG_API_DOMAIN" >/dev/null || fail "--api_domain : $(is_domain "$ARG_API_DOMAIN")"
        API_DOMAIN=$ARG_API_DOMAIN
    else
        ask API_DOMAIN "The domain of the APIs" "$(old_domain BE_HOST_PORT)" is_domain
    fi
    # The web sockets are served on the port of the APIs : the same domain does, another one may.
    if [ -n "$ARG_WS_DOMAIN" ]; then
        is_domain "$ARG_WS_DOMAIN" >/dev/null || fail "--ws_domain : $(is_domain "$ARG_WS_DOMAIN")"
        WS_DOMAIN=$ARG_WS_DOMAIN
    else
        local old_ws
        old_ws="$(old_ws_domain)"
        ask WS_DOMAIN "The domain of the web sockets" "${old_ws:-$API_DOMAIN}" is_domain
    fi
    if [ "$KIND" = PRIMARY ]; then
        if [ -n "$ARG_PANEL_DOMAIN" ]; then
            is_domain "$ARG_PANEL_DOMAIN" >/dev/null || fail "--panel_domain : $(is_domain "$ARG_PANEL_DOMAIN")"
            PANEL_DOMAIN=$ARG_PANEL_DOMAIN
        else
            ask PANEL_DOMAIN "The domain of the admin panel" "$(old_domain_of_panel)" is_domain
        fi
    fi
    # The built-in web server : a domain each, the web sockets on the domain of the APIs, or one domain for the three.
    if [ "$PROXY" = builtin ] && [ "$PANEL_DOMAIN" = "$API_DOMAIN" ] && [ "$WS_DOMAIN" != "$API_DOMAIN" ]; then
        fail "The admin panel and the APIs share $API_DOMAIN : give the web sockets that domain too (one domain for everything), or the admin panel a domain of its own."
    fi
    if [ "$PROXY" = builtin ] && [ "$PANEL_DOMAIN" = "$WS_DOMAIN" ] && [ "$WS_DOMAIN" != "$API_DOMAIN" ]; then
        fail "The admin panel and the web sockets share $WS_DOMAIN : give the APIs that domain too (one domain for everything), or the admin panel a domain of its own."
    fi
    return 0
}
# The domain of the admin panel of an earlier run of the built-in web server.
old_domain_of_panel() { try jq -r '.apiMaker.adminDomain // ""' "$EDGE_FILE"; }
old_domain() { old "$1" | sed -nE 's#^(https|wss)://([^/:]+).*#\2#p'; }
# The domain of the web sockets of an earlier run : the site of the earlier Caddyfile which passes to the port of API
# Maker after the one of the APIs, else BE_WS_HOST_PORT of a .env written before the admin panel took the address of
# the web sockets from BE_HOST_PORT.
old_ws_domain() {
    local found='' port
    if [ -f "$CADDYFILE" ]; then
        port="$(old am__port)"
        found="$(awk -v port="${port:-$DEFAULT_API_PORT}" '
            /^[^ \t#{}][^ \t]* \{$/ { site = $1; next }
            site != "" && $1 == "reverse_proxy" && $2 == "127.0.0.1:" port { if (++apis == 2) { print site; exit } }
            { site = "" }' "$CADDYFILE")"
        [[ "$found" == :* ]] && found='' # a port of Caddy without SSL, no domain
    fi
    printf '%s' "${found:-$(old_domain BE_WS_HOST_PORT)}"
}

ask_environment() {
    ask_yes_no IS_QA "Are you setting up a server of a QA | UAT | PROD environment" no "$ARG_QA"
}

ask_swap() {
    [ "$IN_CONTAINER" = 1 ] && return 0
    local memory_mb swap_mb wanted
    memory_mb="$(awk '/^MemTotal:/ { printf "%d", $2 / 1024 }' /proc/meminfo)"
    swap_mb="$(awk '/^SwapTotal:/ { printf "%d", $2 / 1024 }' /proc/meminfo)"
    # One program, most of its memory is the sandboxes and the databases : as much swap as memory, 2 GB to 8 GB.
    wanted=$memory_mb
    [ "$wanted" -lt 2048 ] && wanted=2048
    [ "$wanted" -gt 8192 ] && wanted=8192
    if [ "$swap_mb" -ge "$wanted" ]; then
        ok "Swap : $swap_mb MB"
        return 0
    fi
    ask_or_default SWAP_MB "The size of the swap file in MB (the server has $swap_mb MB of swap, $memory_mb MB of memory)" "$wanted" is_swap
}
is_swap() { [[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -ge 512 ] && [ "$1" -le 65536 ] || { echo "From 512 to 65536 MB."; return 1; }; }

ask_mongo() {
    if [ -n "$(old am__mongo_db_connection)" ]; then
        ask_yes_no INSTALL_MONGO "Do you want to re-install MongoDB (its data goes)" no "$([ "$ARG_DEFAULT" = 1 ] && echo no)"
        if [ "$INSTALL_MONGO" = no ]; then
            note "MongoDB stays : the connection string of $ENV_FILE is used, no data is lost."
            MONGO_CONNECTION="$(old am__mongo_db_connection)"
            return 0
        fi
    fi
    [ "$ARG_DEFAULT" = 1 ] || section "MongoDB"
    try docker compose --project-name api_maker -f "$CONFIG/mongodb_api_maker.yml" stop >/dev/null
    ask_or_default MONGO_PORT "The port of MongoDB" "$DEFAULT_MONGO_PORT" is_free_mongo_port
    ask_or_default MONGO_USER "The user name of MongoDB" "$DEFAULT_MONGO_USER" is_user_name
    ask_or_default MONGO_PASSWORD "The password of MongoDB" "$(random_text 20)" is_password
    MONGO_CONNECTION="mongodb://$MONGO_USER:$MONGO_PASSWORD@127.0.0.1:$MONGO_PORT/api_maker_db?authSource=admin&replicaSet=rs0&directConnection=true"
}
is_free_mongo_port() { port_number "$1" || return 1; port_is_free "$1" || { echo "Port $1 is taken."; return 1; }; }

ask_redis() {
    if [ -n "$(old am__redisInternal)" ]; then
        ask_yes_no INSTALL_REDIS "Do you want to re-install Redis (its data goes)" no "$([ "$ARG_DEFAULT" = 1 ] && echo no)"
        if [ "$INSTALL_REDIS" = no ]; then
            note "Redis stays : the connection strings of $ENV_FILE are used."
            REDIS_INTERNAL="$(old am__redisInternal)"
            REDIS_EXTERNAL="$(old am__redisExternal)"
            return 0
        fi
    fi
    [ "$ARG_DEFAULT" = 1 ] || section "Redis"
    try docker compose --project-name api_maker -f "$CONFIG/redis_api_maker.yml" stop >/dev/null
    ask_or_default REDIS_PORT "The port of Redis" "$DEFAULT_REDIS_PORT" is_free_redis_port
    ask_or_default REDIS_PASSWORD "The password of Redis" "$(random_text 20)" is_password
    REDIS_INTERNAL="{\"nodes\": [{port:$REDIS_PORT, host:\"127.0.0.1\", pass: \"$REDIS_PASSWORD\"}]}"
    REDIS_EXTERNAL="{\"nodes\": [{port:$REDIS_PORT, host:\"127.0.0.1\", pass: \"$REDIS_PASSWORD\"}], redisValueExpireInSeconds: 7200, maxCharsResToCache: 1000000}"
}
is_free_redis_port() {
    port_number "$1" || return 1
    [ "$1" != "$MONGO_PORT" ] || { echo "It is the port of MongoDB."; return 1; }
    port_is_free "$1" || { echo "Port $1 is taken."; return 1; }
}

ask_api_maker() {
    [ "$ARG_DEFAULT" = 1 ] || section "API Maker"
    local old_port
    old_port="$(old am__port)"
    ask_or_default API_PORT "The port of API Maker (its APIs and its web sockets)" "${old_port:-$DEFAULT_API_PORT}" is_free_api_port
    if [ "$KIND" = PRIMARY ]; then
        local old_panel
        old_panel="$(old am__adminPanel__port)"
        ask_or_default PANEL_PORT "The port of the admin panel" "${old_panel:-$DEFAULT_PANEL_PORT}" is_free_panel_port
    fi
    if [ "$KIND" = PRIMARY ]; then
        ask_secret PASS_COMMUNICATION "passCommunication" "$(old am__passCommunication)" 20 0 "${AM_PASS_COMMUNICATION:-}"
        # A new passJWT has 32 characters : API Maker warns at every start when the key its tokens are signed with (HMAC
        # with SHA-256) is shorter. 20 characters or more are still taken : the passJWT of an installation made before.
        ask_secret PASS_JWT "passJWT" "$(old am__passJWT)" 20 0 "${AM_PASS_JWT:-}" 32
        if [ "$IS_QA" = yes ]; then
            printf '%sNote :%s passDBEncryptDecrypt is the same for every environment of one git repository : give the one of the DEV server.\n' "$C_RED" "$C_OFF"
            ask_secret PASS_DB "passDBEncryptDecrypt (32 characters, the one of the DEV primary server)" "$(old am__passDBEncryptDecrypt)" 32 1 "${AM_PASS_DB_ENCRYPT_DECRYPT:-}"
        else
            ask_secret PASS_DB "passDBEncryptDecrypt (32 characters)" "$(old am__passDBEncryptDecrypt)" 32 0 "${AM_PASS_DB_ENCRYPT_DECRYPT:-}"
        fi
        # An `if`, not `[ … ] && …` : the last command of a function which is a false test makes it fail, and `set -e` stops.
        if [ -n "${AM_SERVER_NAME:-}" ]; then
            is_name "$AM_SERVER_NAME" >/dev/null || fail "AM_SERVER_NAME : $(is_name "$AM_SERVER_NAME")"
            SERVER_NAME=$AM_SERVER_NAME
        fi
    else
        printf '%sNote :%s a secondary server has the secrets of its primary server (in %s there).\n' "$C_RED" "$C_OFF" "$ENV_FILE"
        ask_secret PASS_COMMUNICATION "passCommunication of the primary server" "$(old am__passCommunication)" 20 1 "${AM_PASS_COMMUNICATION:-}"
        ask_secret PASS_JWT "passJWT of the primary server" "$(old am__passJWT)" 20 1 "${AM_PASS_JWT:-}" 32
        ask_secret PASS_DB "passDBEncryptDecrypt of the primary server" "$(old am__passDBEncryptDecrypt)" 32 1 "${AM_PASS_DB_ENCRYPT_DECRYPT:-}"
        local old_name
        old_name="${AM_SERVER_NAME:-$(old am__serverName)}"
        if [ -z "$old_name" ] || [ "$old_name" = primary ] || [ "$old_name" = server1 ]; then old_name=secondary_1; fi
        ask_given SERVER_NAME "The name of this server" "$old_name" is_name "${AM_SERVER_NAME:-}"
        ask_given MONGO_CONNECTION "The MongoDB connection string of API Maker (the one of the primary server)" "$(old am__mongo_db_connection)" is_not_empty "${AM_MONGO_CONNECTION:-}"
        ask_given REDIS_INTERNAL "The internal Redis of API Maker (the one of the primary server)" "$(old am__redisInternal)" is_not_empty "${AM_REDIS_INTERNAL:-}"
        ask_given REDIS_EXTERNAL "The external Redis (optional, empty for none)" "$(old am__redisExternal)" "" "${AM_REDIS_EXTERNAL:-}"
    fi
}
is_not_empty() { [ -n "$1" ] || { echo "It can not be empty."; return 1; }; }
is_free_api_port() {
    port_number "$1" || return 1
    [ "$1" != "$MONGO_PORT" ] && [ "$1" != "$REDIS_PORT" ] || { echo "It is the port of MongoDB or Redis."; return 1; }
    [ "$PROXY" = none ] || { [ "$1" != "$CADDY_API_PORT" ] && [ "$1" != "$CADDY_WS_PORT" ]; } || { echo "The web server in front of API Maker takes ports $CADDY_API_PORT and $CADDY_WS_PORT."; return 1; }
    port_is_free "$1" || { echo "Port $1 is taken."; return 1; }
}
is_free_panel_port() {
    is_free_api_port "$1" || return 1
    [ "$1" != "$API_PORT" ] || { echo "It is the port of the APIs."; return 1; }
}

# The domains of the answers, each once (the web sockets often have the domain of the APIs).
domains_answered() {
    local said='' domain
    for domain in "$API_DOMAIN" "$WS_DOMAIN" "$PANEL_DOMAIN"; do
        [ -n "$domain" ] && [[ ", $said, " != *", $domain, "* ]] && said="${said:+$said, }$domain"
    done
    printf '%s' "$said"
}

# What the installation will be, as answered.
print_answers() {
    local proxy="none : API Maker answers on its own ports"
    if [ "$INSTALL_CADDY" = yes ]; then
        proxy="Caddy, without SSL"
        [ "$INSTALL_SSL" = yes ] && proxy="Caddy with SSL : $(domains_answered)"
    elif [ "$PROXY" = builtin ]; then
        proxy="API Maker's built-in web server, without SSL"
        [ "$INSTALL_SSL" = yes ] && proxy="API Maker's built-in web server with SSL : $(domains_answered)"
        [ "$HTTPS_ON_IP" = yes ] && proxy="API Maker's built-in web server with HTTPS on $SERVER_IP"
        [ "$KIND" = SECONDARY ] && proxy="API Maker's built-in web server : the connections of the primary server ($PRIMARY_IP)"
    fi
    printf '  %-22s %s\n' "Server" "$KIND, $SERVER_IP" "Reverse proxy" "$proxy" "API Maker" "port $API_PORT (APIs and web sockets)"
    [ "$KIND" = PRIMARY ] && printf '  %-22s %s\n' "Admin panel" "port $PANEL_PORT"
    if [ "$KIND" = PRIMARY ]; then
        local moves="kept, moves to the network of the server (no docker-proxy) : it restarts once, about 20 seconds"
        if [ "$INSTALL_MONGO" = yes ]; then printf '  %-22s %s\n' "MongoDB" "a new container on port $MONGO_PORT"
        elif [ "$MONGO_MOVE" = yes ]; then printf '  %-22s %s\n' "MongoDB" "$moves"
        else printf '  %-22s %s\n' "MongoDB" "kept"; fi
        [ "$MONGO_KEY" = yes ] && printf '  %-22s %s\n' "MongoDB key" "a new random key for its replica set (the installer of v3 wrote one public key on every server) : MongoDB restarts once"
        if [ "$INSTALL_REDIS" = yes ]; then printf '  %-22s %s\n' "Redis" "a new container on port $REDIS_PORT"
        elif [ "$REDIS_MOVE" = yes ]; then printf '  %-22s %s\n' "Redis" "$moves"
        else printf '  %-22s %s\n' "Redis" "kept"; fi
    fi
    [ "$IS_QA" = yes ] && printf '  %-22s %s\n' "Environment" "QA | UAT | PROD"
    return 0
}

# ---------------------------------------------------------------------------------------------------- installation

make_folders() {
    mkdir -p "$APP_ROOT/uploads" "$RELEASES" "$CONFIG/bkp_env" "$CONFIG/bkp_caddyfile" "$SERVICE_FOLDER" "$LOGS/install" "$DOCKER_DATA"
}

set_swap() {
    [ "$SWAP_MB" -gt 0 ] || return 0
    swapoff /var/swap.img 2>/dev/null || true
    run "Making a swap file of $SWAP_MB MB" bash -c "
        set -e
        rm -f /var/swap.img
        fallocate -l ${SWAP_MB}M /var/swap.img 2>/dev/null || dd if=/dev/zero of=/var/swap.img bs=1M count=$SWAP_MB status=none
        chmod 600 /var/swap.img
        mkswap /var/swap.img
        swapon /var/swap.img
        grep -qs '^/var/swap.img[[:space:]]' /etc/fstab || echo '/var/swap.img none swap sw 0 0' >> /etc/fstab
    "
}

install_docker() {
    if command -v docker >/dev/null && docker compose version >/dev/null 2>&1; then
        ok "$(docker --version)"
        try systemctl enable --now docker >/dev/null
        return 0
    fi
    run "Installing Docker" bash -c '
        set -e
        for package in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do apt-get remove -y -q $package >/dev/null 2>&1 || true; done
        install -m 0755 -d /etc/apt/keyrings
        curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
        chmod a+r /etc/apt/keyrings/docker.asc
        codename=$(. /etc/os-release && echo "$VERSION_CODENAME")
        # A new Ubuntu release comes before its repository of Docker : the one of the newest LTS works on it.
        curl -fsL -o /dev/null "https://download.docker.com/linux/ubuntu/dists/$codename/Release" || codename=noble
        echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $codename stable" > /etc/apt/sources.list.d/docker.list
        apt-get -o DPkg::Lock::Timeout=600 update -q
        apt-get -o DPkg::Lock::Timeout=600 install -y -q docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
        systemctl enable --now docker
    '
}

# Room for many connections : a WebSocket client is one, and it stays. A server holds about 120 clients of web socket
# events for each MB of its memory (8.4 KB each, its socket in the kernel and its registration in Redis included).
# - Docker makes the kernel track every connection of the server (its firewall rules translate addresses). The table
#   of the tracked connections holds 262,144 of them on a server of 4 GB or more as Linux sets it up, 65,536 on 1 GB,
#   and a connection which closed stays in it for two more minutes : once it is full the kernel drops new connections
#   ("nf_conntrack: table full, dropping packet"), whatever memory is left, SSH included. It gets room for 256
#   connections per MB of memory (131,072 at the least, 16,777,216 at the most : an entry is about 320 bytes, used
#   only while its connection is there), twice the clients the memory holds, so that clients which all come back
#   after a restart find room while the connections they had are still in it ; a closed connection leaves it after
#   30 seconds ; its index has a place for every four of them, so that a full table is looked through as fast as an
#   empty one.
# - Every connection is an open file of API Maker : the service may have as many as the table tracks (1,048,576 at
#   the least), Caddy, which holds two for every client it passes on, twice as many, and Linux gives a process no
#   more than fs.nr_open (1,048,576 as it starts) : it is raised with them. (With 1,048,576 open files, a server of
#   16 GB took about a million clients, with half of its memory left.)
# - API Maker asks for a queue of 16,384 connections waiting to be accepted, and Linux gives no more than
#   net.core.somaxconn (4,096) : the clients which all come back at once after a restart wait there.
# What the server has more of already is kept. In a container the kernel is the one of the host : nothing is set.
OPEN_FILES=1048576
CADDY_OPEN_FILES=1048576
set_network_limits() {
    [ "$IN_CONTAINER" = 1 ] && return 0
    local memory_mb tracked queue now buckets nr_open
    memory_mb="$(awk '/^MemTotal:/ { printf "%d", $2 / 1024 }' /proc/meminfo)"
    tracked=$((memory_mb * 256))
    [ "$tracked" -lt 131072 ] && tracked=131072
    [ "$tracked" -gt 16777216 ] && tracked=16777216
    queue=16384
    try modprobe nf_conntrack
    now="$(try sysctl -n net.netfilter.nf_conntrack_max)"
    if [[ "$now" =~ ^[0-9]+$ ]] && [ "$now" -gt "$tracked" ]; then tracked=$now; fi
    now="$(try sysctl -n net.core.somaxconn)"
    if [[ "$now" =~ ^[0-9]+$ ]] && [ "$now" -gt "$queue" ]; then queue=$now; fi
    buckets=$((tracked / 4))
    now="$(try cat /sys/module/nf_conntrack/parameters/hashsize)"
    if [[ "$now" =~ ^[0-9]+$ ]] && [ "$now" -gt "$buckets" ]; then buckets=$now; fi
    [ "$tracked" -gt "$OPEN_FILES" ] && OPEN_FILES=$tracked
    nr_open=$((OPEN_FILES * 2))
    now="$(try sysctl -n fs.nr_open)"
    if [[ "$now" =~ ^[0-9]+$ ]] && [ "$now" -gt "$nr_open" ]; then nr_open=$now; fi
    # The table is there at boot before its limits are read (Docker would load it later), with its index.
    printf '%s\n' '# Written by the API Maker installer : the table of the tracked connections, loaded before /etc/sysctl.d is read.' \
        'nf_conntrack' >/etc/modules-load.d/api-maker.conf
    printf '%s\n' '# Written by the API Maker installer : the index of the table of the tracked connections.' \
        "options nf_conntrack hashsize=$buckets" >/etc/modprobe.d/api-maker.conf
    try sh -c "echo $buckets > /sys/module/nf_conntrack/parameters/hashsize"
    printf '%s\n' '# Written by the API Maker installer : room for many connections (a WebSocket client is one, and it stays).' \
        "net.netfilter.nf_conntrack_max = $tracked" \
        'net.netfilter.nf_conntrack_tcp_timeout_time_wait = 30' \
        "net.core.somaxconn = $queue" \
        "net.ipv4.tcp_max_syn_backlog = $queue" \
        "fs.nr_open = $nr_open" >/etc/sysctl.d/90-api-maker.conf
    if ! sysctl -q -p /etc/sysctl.d/90-api-maker.conf >>"$INSTALL_LOG" 2>&1; then
        warn "The limits of the network could not all be set (/etc/sysctl.d/90-api-maker.conf) : the log of the installer says why."
    fi
    # A service may not be given more open files than Linux gives a process : what it gives now decides.
    now="$(try sysctl -n fs.nr_open)"
    if [[ "$now" =~ ^[0-9]+$ ]]; then
        [ "$OPEN_FILES" -gt "$now" ] && OPEN_FILES=$now
        CADDY_OPEN_FILES=$((OPEN_FILES * 2))
        [ "$CADDY_OPEN_FILES" -gt "$now" ] && CADDY_OPEN_FILES=$now
    fi
    [ "$OPEN_FILES" -lt 1048576 ] && OPEN_FILES=1048576
    [ "$CADDY_OPEN_FILES" -lt 1048576 ] && CADDY_OPEN_FILES=1048576
    ok "Network : room for $(try sysctl -n net.netfilter.nf_conntrack_max) tracked connections, $OPEN_FILES open files for API Maker, a queue of $(try sysctl -n net.core.somaxconn) waiting to be accepted"
}

# ---------------------------------------------------------------------------------------------------- MongoDB and Redis

# MongoDB and Redis share the network of the server (network_mode: host), as Launchpad runs them : each listens on its
# port of the server itself. A port Docker publishes goes through docker-proxy, a program that copies every byte between
# the two sides : about a quarter fewer reads of a whole table a second on one shared CPU.

# write_mongo_compose IMAGE PORT USER PASSWORD : the compose file of MongoDB.
write_mongo_compose() {
    local image=$1 port=$2 user=$3 password=$4
    cat >"$CONFIG/mongodb_api_maker.yml" <<EOF
# Written by the API Maker installer : the MongoDB of API Maker, a replica set of one member (rs0), on port $port of the
# server (the network of the server : no docker-proxy between API Maker and MongoDB).
services:
    am_mongodb:
        image: $image
        restart: always
        container_name: $MONGODB_CONTAINER
        network_mode: host
        command: [ "--replSet", "rs0", "--bind_ip_all", "--port", "$port", "--keyFile", "/opt/keyfile" ]
        environment:
            - MONGO_INITDB_ROOT_USERNAME=$user
            - MONGO_INITDB_ROOT_PASSWORD=$password
            - MONGO_REPLICA_SET_NAME=rs0
        healthcheck:
            test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'127.0.0.1:$port'}]}) }" | mongosh -u "$user" -p "$password" --port $port --quiet
            interval: 86400s
            timeout: 30s
            start_period: 5s
            retries: 10
        volumes:
            - $DOCKER_DATA/mongodb_api_maker/data:/data/db
            - $DOCKER_DATA/mongodb_api_maker/configdb:/data/configdb
            - ./keyfile:/opt/keyfile
        logging:
            driver: "json-file"
            options:
                max-size: "5m"
                max-file: "3"
EOF
}

# write_redis_compose IMAGE PORT PASSWORD : the compose file of Redis.
write_redis_compose() {
    local image=$1 port=$2 password=$3
    cat >"$CONFIG/redis_api_maker.yml" <<EOF
# Written by the API Maker installer : the Redis of API Maker, on port $port of the server (the network of the server :
# no docker-proxy between API Maker and Redis).
services:
    redis_api_maker:
        image: '$image'
        restart: always
        container_name: $REDIS_CONTAINER
        network_mode: host
        command: redis-server --port $port --loglevel warning --requirepass $password
        volumes:
            - $DOCKER_DATA/redis_api_maker:/data
        logging:
            driver: "json-file"
            options:
                max-size: "5m"
                max-file: "3"
EOF
}

# old_mongo_compose IMAGE PORT USER PASSWORD and old_redis_compose IMAGE PORT PASSWORD : the compose files every earlier
# version of this installer wrote (Docker published the ports). A file that is not exactly one of them was changed by
# hand : it is never rewritten.
old_mongo_compose() {
    local image=$1 port=$2 user=$3 password=$4
    cat <<EOF
# Written by the API Maker installer : the MongoDB of API Maker, a replica set of one member (rs0).
services:
    am_mongodb:
        image: $image
        restart: always
        container_name: $MONGODB_CONTAINER
        command: [ "--replSet", "rs0", "--bind_ip_all", "--port", "27017", "--keyFile", "/opt/keyfile" ]
        ports:
            - $port:27017
        environment:
            - MONGO_INITDB_ROOT_USERNAME=$user
            - MONGO_INITDB_ROOT_PASSWORD=$password
            - MONGO_REPLICA_SET_NAME=rs0
        healthcheck:
            test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'127.0.0.1:27017'}]}) }" | mongosh -u "$user" -p "$password" --port 27017 --quiet
            interval: 86400s
            timeout: 30s
            start_period: 5s
            retries: 10
        volumes:
            - $DOCKER_DATA/mongodb_api_maker/data:/data/db
            - $DOCKER_DATA/mongodb_api_maker/configdb:/data/configdb
            - ./keyfile:/opt/keyfile
        logging:
            driver: "json-file"
            options:
                max-size: "5m"
                max-file: "3"
EOF
}
old_redis_compose() {
    local image=$1 port=$2 password=$3
    cat <<EOF
# Written by the API Maker installer : the Redis of API Maker.
networks:
    redis_api_maker-network:
        driver: bridge
services:
    redis_api_maker:
        image: '$image'
        restart: always
        container_name: $REDIS_CONTAINER
        ports:
            - '$port:6379'
        command: redis-server --loglevel warning --requirepass $password
        volumes:
            - $DOCKER_DATA/redis_api_maker:/data
        networks:
            - redis_api_maker-network
        logging:
            driver: "json-file"
            options:
                max-size: "5m"
                max-file: "3"
EOF
}

# ---- ufw : Docker sends what reaches a port it publishes to the container past ufw (its own rules come first). On the
# network of the server, ufw decides : a port with no rule of ufw is allowed, the reach it had through Docker.

# (The outputs are read whole first : with pipefail, a reader that stops early, like head or grep -q, makes the command
# that still writes fail, and the answer with it.)
ufw_active() {
    local status
    command -v ufw >/dev/null 2>&1 || return 1
    status=$(LC_ALL=C ufw status 2>/dev/null || true)
    [[ "$status" == "Status: active"* ]]
}
# ufw_has_rule PORT : ufw has a rule of its own for PORT (allow, deny, from some addresses only…).
ufw_has_rule() {
    local status
    status=$(LC_ALL=C ufw status 2>/dev/null || true)
    awk -v p="$1" 'NR > 1 && ($1 == p || $1 == p "/tcp") { found = 1 } END { exit !found }' <<<"$status"
}
# docker_nat_publishes PORT : Docker sends what reaches PORT to a container with its rules of NAT (ufw does not see it).
docker_nat_publishes() {
    local rules
    rules=$(iptables -t nat -S DOCKER 2>/dev/null || true)
    grep -Eq -- "--dport $1 (.* )?-j DNAT" <<<"$rules"
}
# docker_without_iptables : Docker writes no rules of the firewall (ufw always filtered the ports it publishes).
docker_without_iptables() { grep -Eqs '"iptables"[[:space:]]*:[[:space:]]*false' /etc/docker/daemon.json; }

UFW_ADDED=' '
# ufw_allow_like_docker PORT WHAT FRESH : with ufw on, PORT (WHAT) gets the reach it had through Docker. FRESH : a new
# MongoDB or Redis (earlier versions of this installer published its port), otherwise one that moves now.
ufw_allow_like_docker() {
    local port=$1 what=$2 fresh=$3
    ufw_active || return 0
    if ufw_has_rule "$port"; then
        note "ufw : port $port ($what) keeps the rules ufw has for it, which decide from now on (Docker let every address past them)."
        return 0
    fi
    if [ "$fresh" = yes ]; then
        docker_without_iptables && return 0
    elif ! docker_nat_publishes "$port"; then
        note "ufw : ufw decides from now on who reaches port $port ($what) from other servers : ufw allow $port/tcp lets every address in."
        return 0
    fi
    if ufw allow "$port/tcp" comment "API Maker : $what" >>"$INSTALL_LOG" 2>&1; then
        UFW_ADDED="$UFW_ADDED$port "
        note "ufw : port $port ($what) allowed, the reach it had through Docker. To let your secondary servers only in : ufw delete allow $port/tcp, then ufw allow from <their address> to any port $port proto tcp"
    else
        warn "ufw : port $port ($what) could not be allowed : other servers reach it once ufw lets them in (ufw allow $port/tcp)."
    fi
}
# ufw_undo PORT : the rule ufw_allow_like_docker added for PORT goes.
ufw_undo() {
    case "$UFW_ADDED" in
        *" $1 "*)
            ufw delete allow "$1/tcp" >>"$INSTALL_LOG" 2>&1 || true
            UFW_ADDED="${UFW_ADDED/ $1 / }"
            ;;
    esac
}

# ---- a new MongoDB and Redis

# mongo_first_user IMAGE : the data of a new MongoDB gets its user. The image creates it the first time it starts
# (MONGO_INITDB_ROOT_*), with a temporary MongoDB on 127.0.0.1:27017 : that first start runs in a container without
# network, where that port is its own (on the network of the server, another MongoDB may have it).
mongo_first_user() {
    local image=$1 name=am_installer_mongo_init out='' i
    local js='try { db.getSiblingDB("admin").auth(process.env.AM_USER, process.env.AM_PASSWORD); print(db.hello().isreplicaset === true ? "ready" : "first") } catch (e) { print("wait") }'
    docker rm -f "$name" >/dev/null 2>&1 || true
    MONGO_INITDB_ROOT_USERNAME="$MONGO_USER" MONGO_INITDB_ROOT_PASSWORD="$MONGO_PASSWORD" \
        docker run -d --name "$name" --network none -e MONGO_INITDB_ROOT_USERNAME -e MONGO_INITDB_ROOT_PASSWORD \
        -v "$DOCKER_DATA/mongodb_api_maker/data:/data/db" -v "$DOCKER_DATA/mongodb_api_maker/configdb:/data/configdb" \
        -v "$CONFIG/keyfile:/opt/keyfile" "$image" --replSet rs0 --bind_ip_all --port 27017 --keyFile /opt/keyfile >/dev/null || return 1
    for i in $(seq 1 120); do
        # Ready : the user exists and MongoDB runs as a member of a replica set (the temporary one runs without).
        out=$(AM_USER="$MONGO_USER" AM_PASSWORD="$MONGO_PASSWORD" docker exec -e AM_USER -e AM_PASSWORD "$name" \
            mongosh --quiet --norc --port 27017 --eval "$js" 2>/dev/null || true)
        grep -qx ready <<<"$out" && break
        [ "$(try docker inspect -f '{{.State.Running}}' "$name")" = true ] || break
        sleep 2
    done
    grep -qx ready <<<"$out" || docker logs --tail 40 "$name" 2>&1 || true
    docker stop -t 60 "$name" >/dev/null 2>&1 || true
    docker rm -f "$name" >/dev/null 2>&1 || true
    grep -qx ready <<<"$out" || { echo 'MongoDB did not create its user in 4 minutes'; return 1; }
}

# mongo_fresh IMAGE : a new MongoDB, its data folder empty first, its user created, on the network of the server.
mongo_fresh() {
    local image=$1 file="$CONFIG/mongodb_api_maker.yml"
    docker compose --project-name api_maker -f "$file" down 2>/dev/null || true
    docker rm -f "$MONGODB_CONTAINER" 2>/dev/null || true
    rm -rf "$DOCKER_DATA/mongodb_api_maker" || return 1
    mongo_first_user "$image" || return 1
    docker compose --project-name api_maker -f "$file" up -d
}

install_mongo() {
    [ "$KIND" = PRIMARY ] || return 0
    if [ "$INSTALL_MONGO" = no ]; then
        renew_mongo_key
        if [ "$MONGO_MOVE" = yes ]; then move_mongo; fi
        return 0
    fi
    local keyfile="$CONFIG/keyfile"
    # The key the members of the replica set know each other by : one member, any key.
    openssl rand -base64 756 | tr -d '\n' | fold -w 64 >"$keyfile"
    chmod 600 "$keyfile"
    chown 999:999 "$keyfile"
    write_mongo_compose "mongo:$ARG_MONGO_VERSION" "$MONGO_PORT" "$MONGO_USER" "$MONGO_PASSWORD"
    run "Installing MongoDB $ARG_MONGO_VERSION" mongo_fresh "mongo:$ARG_MONGO_VERSION"
    # API Maker checks the replica set once when it starts : it has to be ready first.
    run "Waiting for the replica set of MongoDB" bash -c "
        for attempt in \$(seq 1 120); do
            if docker exec $MONGODB_CONTAINER mongosh -u '$MONGO_USER' -p '$MONGO_PASSWORD' --authenticationDatabase admin --port $MONGO_PORT --quiet \
                --eval \"try { print(rs.status().set) } catch (e) { rs.initiate({ _id: 'rs0', members: [{ _id: 0, host: '127.0.0.1:$MONGO_PORT' }] }) }\" 2>/dev/null | grep -qx rs0; then
                exit 0
            fi
            sleep 2
        done
        echo 'the replica set did not start in 4 minutes'
        exit 1
    "
    ufw_allow_like_docker "$MONGO_PORT" MongoDB yes
}

install_redis() {
    [ "$KIND" = PRIMARY ] || return 0
    if [ "$INSTALL_REDIS" = no ]; then
        if [ "$REDIS_MOVE" = yes ]; then move_redis; fi
        return 0
    fi
    write_redis_compose 'redis:7.0.5-alpine' "$REDIS_PORT" "$REDIS_PASSWORD"
    run "Installing Redis" bash -c "
        set -e
        docker compose --project-name api_maker -f '$CONFIG/redis_api_maker.yml' down 2>/dev/null || true
        docker rm -f $REDIS_CONTAINER 2>/dev/null || true
        rm -rf '$DOCKER_DATA/redis_api_maker'
        docker compose --project-name api_maker -f '$CONFIG/redis_api_maker.yml' up -d
    "
    ufw_allow_like_docker "$REDIS_PORT" Redis yes
}

# ---- MongoDB and Redis of an earlier installer (Docker published their ports) : they move to the network of the server,
# on the same ports, with the same data, users and passwords : every API Maker server keeps its settings. They restart
# once (about 20 seconds). Only what this installer made moves; when a step fails, everything goes back as it was and
# the installation goes on. plan_mongo_move and plan_redis_move look (nothing changes), before the answers are shown.

MONGO_MOVE='' MONGO_MOVE_IMAGE='' MONGO_MOVE_PORT='' MONGO_MOVE_USER='' MONGO_MOVE_PASSWORD='' MONGO_MOVE_MEMBER='' MONGO_MOVE_DBS=''
MONGO_MOVE_OWNER='' MONGO_MOVE_BACKUP='' MONGO_MOVE_RENAMED=0
REDIS_MOVE='' REDIS_MOVE_IMAGE='' REDIS_MOVE_PORT='' REDIS_MOVE_PASSWORD='' REDIS_MOVE_BACKUP='' REDIS_MOVE_DUMP='' REDIS_MOVE_STOPPED=0

# published_port CONTAINER PORT/tcp : the port of the server Docker publishes a port of the container on ("" : none).
published_port() {
    try docker inspect -f '{{range $p, $b := .HostConfig.PortBindings}}{{if eq $p "'"$2"'"}}{{range $b}}{{.HostPort}}{{"\n"}}{{end}}{{end}}{{end}}' "$1" | head -n1
}
# mount_source CONTAINER DESTINATION : the folder of the server mounted at DESTINATION in the container.
mount_source() { try docker inspect -f '{{range .Mounts}}{{if eq .Destination "'"$2"'"}}{{.Source}}{{end}}{{end}}' "$1"; }
network_of() { try docker inspect -f '{{.HostConfig.NetworkMode}}' "$1"; }
command_of() { try docker inspect -f '{{json .Config.Cmd}}' "$1"; }
is_running() { [ "$(try docker inspect -f '{{.State.Running}}' "$1")" = true ]; }
wait_port_free() {
    local i
    for i in $(seq 1 10); do port_is_free "$1" && return 0; sleep 1; done
    echo "port $1 is still taken"
    return 1
}
progress_start() {
    if [ -t 1 ]; then printf '⏳  %s…' "$1"; else printf '⏳  %s…\n' "$1"; fi
    printf '\n==== %s : %s\n' "$(date '+%F %T')" "$1" >>"$INSTALL_LOG"
}
progress_end() { if [ -t 1 ]; then printf '\r\e[K'; fi; }

# mongo_eval CONTAINER PORT USER PASSWORD JS : mongosh in the container, signed in as USER (the password in the
# environment of the command, never on a command line).
mongo_eval() {
    local js="db.getSiblingDB(\"admin\").auth(process.env.AM_USER, process.env.AM_PASSWORD); $5"
    AM_USER="$3" AM_PASSWORD="$4" docker exec -e AM_USER -e AM_PASSWORD "$1" mongosh --quiet --norc --port "$2" --eval "$js"
}
# What MongoDB says of itself : its replica set (rs, its name, its members, the first one) and its databases.
readonly MONGO_FACTS_JS='const c = rs.conf();
print("rs\t" + c._id + "\t" + c.members.length + "\t" + c.members[0].host);
print("dbs\t" + db.adminCommand({ listDatabases: 1, nameOnly: true }).databases.map((d) => d.name).sort().join(","));'

plan_mongo_move() {
    MONGO_MOVE=''
    [ "$KIND" = PRIMARY ] && [ "$INSTALL_MONGO" = no ] || return 0
    local network
    network="$(network_of "$MONGODB_CONTAINER")"
    [ -n "$network" ] && [ "$network" != host ] || return 0
    local stays="MongoDB stays as it is, behind docker-proxy" re='^mongodb://([A-Za-z0-9_]+):([A-Za-z0-9_]+)@(127\.0\.0\.1|localhost):([0-9]+)/'
    if ! [[ "$MONGO_CONNECTION" =~ $re ]]; then
        note "$stays : API Maker does not reach it on 127.0.0.1 with a user and a password of letters and digits ($ENV_FILE)."
        return 0
    fi
    local user=${BASH_REMATCH[1]} password=${BASH_REMATCH[2]} port=${BASH_REMATCH[4]} file="$CONFIG/mongodb_api_maker.yml" image
    image="$(try docker inspect -f '{{.Config.Image}}' "$MONGODB_CONTAINER")"
    if [ -z "$image" ] || [ ! -f "$file" ] || [ "$(cat "$file")" != "$(old_mongo_compose "$image" "$port" "$user" "$password")" ]; then
        note "$stays : its compose file ($file) is not the one this installer wrote, or it was changed."
        return 0
    fi
    if [ ! -f "$CONFIG/keyfile" ] || [ "$(published_port "$MONGODB_CONTAINER" 27017/tcp)" != "$port" ] ||
        [ "$(command_of "$MONGODB_CONTAINER")" != '["--replSet","rs0","--bind_ip_all","--port","27017","--keyFile","/opt/keyfile"]' ] ||
        [ "$(mount_source "$MONGODB_CONTAINER" /data/db)" != "$DOCKER_DATA/mongodb_api_maker/data" ] ||
        [ "$(mount_source "$MONGODB_CONTAINER" /data/configdb)" != "$DOCKER_DATA/mongodb_api_maker/configdb" ] ||
        [ "$(mount_source "$MONGODB_CONTAINER" /opt/keyfile)" != "$CONFIG/keyfile" ]; then
        note "$stays : its container ($MONGODB_CONTAINER) is not the one of $file."
        return 0
    fi
    if ! is_running "$MONGODB_CONTAINER"; then
        note "$stays : it does not run now (docker start $MONGODB_CONTAINER, then run the installer again to move it)."
        return 0
    fi
    if ! docker run --rm --network none --entrypoint sh "$image" -c 'command -v mongosh' >/dev/null 2>&1; then
        note "$stays : its image ($image) has no mongosh."
        return 0
    fi
    local out rs
    out=$(mongo_eval "$MONGODB_CONTAINER" 27017 "$user" "$password" "$MONGO_FACTS_JS" 2>&1 || true)
    rs=$(grep $'^rs\t' <<<"$out" | head -n1 || true)
    if [ "$(cut -f2 <<<"$rs")" != rs0 ] || [ "$(cut -f3 <<<"$rs")" != 1 ]; then
        note "$stays : it does not answer as the replica set rs0 of one member ($(tail -n1 <<<"$out" | cut -c1-200))."
        return 0
    fi
    MONGO_MOVE=yes MONGO_MOVE_IMAGE=$image MONGO_MOVE_PORT=$port MONGO_MOVE_USER=$user MONGO_MOVE_PASSWORD=$password
    MONGO_MOVE_MEMBER=$(cut -f4 <<<"$rs")
    MONGO_MOVE_DBS=$(grep $'^dbs\t' <<<"$out" | head -n1 | cut -f2 || true)
}

plan_redis_move() {
    REDIS_MOVE=''
    [ "$KIND" = PRIMARY ] && [ "$INSTALL_REDIS" = no ] || return 0
    local network
    network="$(network_of "$REDIS_CONTAINER")"
    [ -n "$network" ] && [ "$network" != host ] || return 0
    local stays="Redis stays as it is, behind docker-proxy" re='port: *([0-9]+), *host: *"(127\.0\.0\.1|localhost)", *pass: *"([A-Za-z0-9_]+)"'
    if [ "$(grep -o 'port *:' <<<"$REDIS_INTERNAL" | wc -l)" -ne 1 ] || ! [[ "$REDIS_INTERNAL" =~ $re ]]; then
        note "$stays : API Maker does not reach it as one node on 127.0.0.1 with a password of letters and digits ($ENV_FILE)."
        return 0
    fi
    local port=${BASH_REMATCH[1]} password=${BASH_REMATCH[3]} file="$CONFIG/redis_api_maker.yml" image
    image="$(try docker inspect -f '{{.Config.Image}}' "$REDIS_CONTAINER")"
    if [ -z "$image" ] || [ ! -f "$file" ] || [ "$(cat "$file")" != "$(old_redis_compose "$image" "$port" "$password")" ]; then
        note "$stays : its compose file ($file) is not the one this installer wrote, or it was changed."
        return 0
    fi
    if [ "$(published_port "$REDIS_CONTAINER" 6379/tcp)" != "$port" ] ||
        [ "$(command_of "$REDIS_CONTAINER")" != "[\"redis-server\",\"--loglevel\",\"warning\",\"--requirepass\",\"$password\"]" ] ||
        [ "$(mount_source "$REDIS_CONTAINER" /data)" != "$DOCKER_DATA/redis_api_maker" ]; then
        note "$stays : its container ($REDIS_CONTAINER) is not the one of $file."
        return 0
    fi
    if ! is_running "$REDIS_CONTAINER"; then
        note "$stays : it does not run now (docker start $REDIS_CONTAINER, then run the installer again to move it)."
        return 0
    fi
    REDIS_MOVE=yes REDIS_MOVE_IMAGE=$image REDIS_MOVE_PORT=$port REDIS_MOVE_PASSWORD=$password
}

# mongo_member_host IMAGE OWNER HOST : the replica set of the data of MongoDB names its member HOST (the address MongoDB
# knows itself by : 127.0.0.1 and the port it listens on). MongoDB runs alone on the data for it, without network and
# without its replica set, then stops.
mongo_member_host() {
    local image=$1 owner=$2 host=$3 name=am_installer_mongo_member out i
    local js='const l = db.getSiblingDB("local"), c = l.system.replset.findOne();
if (!c || c.members.length !== 1) { print("member\tnone"); quit(0); }
const was = c.members[0].host;
if (was !== process.env.AM_MEMBER) { l.system.replset.updateOne({ _id: c._id }, { $set: { "members.0.host": process.env.AM_MEMBER } }); }
print("member\tok\t" + was + "\t" + l.system.replset.findOne().members[0].host);'
    docker rm -f "$name" >/dev/null 2>&1 || true
    docker run -d --name "$name" --network none --user "$owner" \
        -v "$DOCKER_DATA/mongodb_api_maker/data:/data/db" -v "$DOCKER_DATA/mongodb_api_maker/configdb:/data/configdb" \
        --entrypoint mongod "$image" --dbpath /data/db --port 27999 --bind_ip 127.0.0.1 \
        --setParameter disableLogicalSessionCacheRefresh=true >/dev/null || return 1
    for i in $(seq 1 120); do
        out=$(docker exec "$name" mongosh --quiet --norc --port 27999 --eval 'db.adminCommand({ ping: 1 }).ok' 2>/dev/null || true)
        grep -qx 1 <<<"$out" && break
        is_running "$name" || break
        sleep 1
    done
    out=$(docker exec -e AM_MEMBER="$host" "$name" mongosh --quiet --norc --port 27999 --eval "$js" 2>&1 || true)
    printf '%s\n' "$out"
    docker stop -t 60 "$name" >/dev/null 2>&1 || true
    docker rm -f "$name" >/dev/null 2>&1 || true
    grep -qx "member"$'\t'"ok"$'\t'".*"$'\t'"$host" <<<"$out"
}

# mongo_wait_primary CONTAINER PORT USER PASSWORD : MongoDB answers as the primary of its replica set (4 minutes at most).
mongo_wait_primary() {
    local _ out
    for _ in $(seq 1 120); do
        out=$(mongo_eval "$1" "$2" "$3" "$4" 'print(db.hello().isWritablePrimary)' 2>/dev/null || true)
        grep -qx true <<<"$out" && return 0
        sleep 2
    done
    echo 'MongoDB is not the primary of its replica set after 4 minutes'
    return 1
}

# mongo_move : MongoDB stops, its member is renamed, it starts on the network of the server, becomes the primary of its
# replica set again, and has every database of before.
mongo_move() {
    local file="$CONFIG/mongodb_api_maker.yml" out now name
    docker compose --project-name api_maker -f "$file" down --timeout 60 || return 1
    docker rm -f "$MONGODB_CONTAINER" 2>/dev/null || true
    wait_port_free "$MONGO_MOVE_PORT" || return 1
    MONGO_MOVE_RENAMED=1
    mongo_member_host "$MONGO_MOVE_IMAGE" "$MONGO_MOVE_OWNER" "127.0.0.1:$MONGO_MOVE_PORT" || return 1
    write_mongo_compose "$MONGO_MOVE_IMAGE" "$MONGO_MOVE_PORT" "$MONGO_MOVE_USER" "$MONGO_MOVE_PASSWORD"
    docker compose --project-name api_maker -f "$file" up -d || return 1
    mongo_wait_primary "$MONGODB_CONTAINER" "$MONGO_MOVE_PORT" "$MONGO_MOVE_USER" "$MONGO_MOVE_PASSWORD" || return 1
    out=$(mongo_eval "$MONGODB_CONTAINER" "$MONGO_MOVE_PORT" "$MONGO_MOVE_USER" "$MONGO_MOVE_PASSWORD" "$MONGO_FACTS_JS" 2>&1 || true)
    printf '%s\n' "$out"
    if ! grep -qx "rs"$'\t'"rs0"$'\t'"1"$'\t'"127.0.0.1:$MONGO_MOVE_PORT" <<<"$out"; then
        echo 'the replica set does not name its member 127.0.0.1:'"$MONGO_MOVE_PORT"
        return 1
    fi
    now=",$(grep $'^dbs\t' <<<"$out" | head -n1 | cut -f2 || true),"
    while IFS= read -r name; do
        [ -n "$name" ] || continue
        case "$now" in *",$name,"*) ;; *) echo "the database $name is not there"; return 1 ;; esac
    done < <(tr ',' '\n' <<<"$MONGO_MOVE_DBS")
}

# mongo_move_back : MongoDB as it was (its compose file, its member, its published port), and the primary again.
mongo_move_back() {
    local file="$CONFIG/mongodb_api_maker.yml"
    docker compose --project-name api_maker -f "$file" down --timeout 60 || true
    docker rm -f "$MONGODB_CONTAINER" 2>/dev/null || true
    if [ "$MONGO_MOVE_RENAMED" = 1 ]; then
        mongo_member_host "$MONGO_MOVE_IMAGE" "$MONGO_MOVE_OWNER" "$MONGO_MOVE_MEMBER" || return 1
    fi
    cp -p "$MONGO_MOVE_BACKUP" "$file" || return 1
    docker compose --project-name api_maker -f "$file" up -d || return 1
    mongo_wait_primary "$MONGODB_CONTAINER" 27017 "$MONGO_MOVE_USER" "$MONGO_MOVE_PASSWORD"
}

move_mongo() {
    local file="$CONFIG/mongodb_api_maker.yml"
    MONGO_MOVE_OWNER="$(stat -c %u:%g "$DOCKER_DATA/mongodb_api_maker/data" 2>/dev/null || true)"
    MONGO_MOVE_BACKUP="$file.before-host-network.$(date '+%Y-%m-%d_%H-%M-%S')"
    MONGO_MOVE_RENAMED=0
    if [ -z "$MONGO_MOVE_OWNER" ] || ! cp -p "$file" "$MONGO_MOVE_BACKUP"; then
        warn "MongoDB stays as it is, behind docker-proxy : its compose file could not be copied first."
        return 0
    fi
    # Before the switch : the secondary servers keep reaching it.
    ufw_allow_like_docker "$MONGO_MOVE_PORT" MongoDB no
    progress_start "MongoDB : moving to the network of the server"
    if mongo_move >>"$INSTALL_LOG" 2>&1; then
        progress_end
        ok "MongoDB : on port $MONGO_MOVE_PORT of the server itself, no docker-proxy (its compose file of before : $MONGO_MOVE_BACKUP)"
        return 0
    fi
    progress_end
    printf '\n==== %s : MongoDB : putting it back as it was\n' "$(date '+%F %T')" >>"$INSTALL_LOG"
    if ! mongo_move_back >>"$INSTALL_LOG" 2>&1; then
        fail "MongoDB could not move to the network of the server, nor run again as it was. Its compose file of before : $MONGO_MOVE_BACKUP ; its replica set named its member $MONGO_MOVE_MEMBER."
    fi
    ufw_undo "$MONGO_MOVE_PORT"
    warn "MongoDB could not move to the network of the server : it runs as it was, behind docker-proxy (the log of the installer says why)."
}

# redis_cli CONTAINER PORT PASSWORD ARGS… : redis-cli in the container (the password in the environment of the command).
redis_cli() {
    local container=$1 port=$2 password=$3
    shift 3
    REDISCLI_AUTH="$password" docker exec -e REDISCLI_AUTH "$container" redis-cli --no-auth-warning -p "$port" "$@"
}
# redis_keys CONTAINER PORT PASSWORD : the keys of every database of Redis, then how many of them do not expire.
redis_keys() {
    redis_cli "$1" "$2" "$3" INFO keyspace 2>/dev/null | tr -d '\r' |
        awk -F'[:=,]' '/^# Keyspace/ { ok = 1 } /^db[0-9]+:/ { keys += $3; expires += $5 } END { if (!ok) exit 1; print keys + 0, keys - expires }'
}
redis_wait() {
    local _ out
    for _ in $(seq 1 60); do
        out=$(redis_cli "$1" "$2" "$3" PING 2>/dev/null || true)
        grep -qx PONG <<<"${out//$'\r'/}" && return 0
        sleep 1
    done
    echo 'Redis does not answer after a minute'
    return 1
}

# redis_move : Redis writes its data and stops, starts on the network of the server, and holds every key of before that
# does not expire.
redis_move() {
    local file="$CONFIG/redis_api_maker.yml" data="$DOCKER_DATA/redis_api_maker" before after saved
    saved=$(redis_cli "$REDIS_CONTAINER" 6379 "$REDIS_MOVE_PASSWORD" SAVE 2>&1 || true)
    grep -qx OK <<<"${saved//$'\r'/}" || { echo "Redis did not save its data : $saved"; return 1; }
    before=$(redis_keys "$REDIS_CONTAINER" 6379 "$REDIS_MOVE_PASSWORD") || { echo 'Redis does not say what it holds'; return 1; }
    echo "keys before : ${before% *}, ${before#* } of them do not expire"
    docker compose --project-name api_maker -f "$file" down --timeout 60 || return 1
    docker rm -f "$REDIS_CONTAINER" 2>/dev/null || true
    REDIS_MOVE_STOPPED=1
    if [ -f "$data/dump.rdb" ]; then cp -p "$data/dump.rdb" "$REDIS_MOVE_DUMP" || return 1; fi
    wait_port_free "$REDIS_MOVE_PORT" || return 1
    write_redis_compose "$REDIS_MOVE_IMAGE" "$REDIS_MOVE_PORT" "$REDIS_MOVE_PASSWORD"
    docker compose --project-name api_maker -f "$file" up -d || return 1
    redis_wait "$REDIS_CONTAINER" "$REDIS_MOVE_PORT" "$REDIS_MOVE_PASSWORD" || return 1
    after=$(redis_keys "$REDIS_CONTAINER" "$REDIS_MOVE_PORT" "$REDIS_MOVE_PASSWORD") || { echo 'Redis does not say what it holds'; return 1; }
    echo "keys after : ${after% *}"
    [ "${after% *}" -ge "${before#* }" ] || { echo "Redis holds ${after% *} keys, ${before#* } of before do not expire"; return 1; }
}

# redis_move_back : Redis as it was (its compose file, its data of before, its published port), answering again.
redis_move_back() {
    local file="$CONFIG/redis_api_maker.yml" data="$DOCKER_DATA/redis_api_maker"
    docker compose --project-name api_maker -f "$file" down --timeout 60 || true
    docker rm -f "$REDIS_CONTAINER" 2>/dev/null || true
    if [ "$REDIS_MOVE_STOPPED" = 1 ] && [ -f "$REDIS_MOVE_DUMP" ]; then
        cp -p "$REDIS_MOVE_DUMP" "$data/dump.rdb" || return 1
    fi
    cp -p "$REDIS_MOVE_BACKUP" "$file" || return 1
    docker compose --project-name api_maker -f "$file" up -d || return 1
    redis_wait "$REDIS_CONTAINER" 6379 "$REDIS_MOVE_PASSWORD"
}

move_redis() {
    local file="$CONFIG/redis_api_maker.yml" stamp
    stamp=$(date '+%Y-%m-%d_%H-%M-%S')
    REDIS_MOVE_BACKUP="$file.before-host-network.$stamp"
    REDIS_MOVE_DUMP="$DOCKER_DATA/redis_api_maker/dump.rdb.before-host-network.$stamp"
    REDIS_MOVE_STOPPED=0
    if ! cp -p "$file" "$REDIS_MOVE_BACKUP"; then
        warn "Redis stays as it is, behind docker-proxy : its compose file could not be copied first."
        return 0
    fi
    ufw_allow_like_docker "$REDIS_MOVE_PORT" Redis no
    progress_start "Redis : moving to the network of the server"
    if redis_move >>"$INSTALL_LOG" 2>&1; then
        progress_end
        rm -f "$REDIS_MOVE_DUMP"
        ok "Redis : on port $REDIS_MOVE_PORT of the server itself, no docker-proxy (its compose file of before : $REDIS_MOVE_BACKUP)"
        return 0
    fi
    progress_end
    printf '\n==== %s : Redis : putting it back as it was\n' "$(date '+%F %T')" >>"$INSTALL_LOG"
    if ! redis_move_back >>"$INSTALL_LOG" 2>&1; then
        fail "Redis could not move to the network of the server, nor run again as it was. Its compose file of before : $REDIS_MOVE_BACKUP ; its data of before : $REDIS_MOVE_DUMP"
    fi
    rm -f "$REDIS_MOVE_DUMP"
    ufw_undo "$REDIS_MOVE_PORT"
    warn "Redis could not move to the network of the server : it runs as it was, behind docker-proxy (the log of the installer says why)."
}

# ---- The key of the replica set of MongoDB. The installer of API Maker v3 (apimaker.dev/v1/install.ts) wrote the same
# key on every server, and that key is public : whoever reaches the port of MongoDB signs in with it as the internal user
# of the replica set, which has every right (Docker published that port past ufw). A MongoDB that stays and still has
# that key gets a new random one, and restarts once : its data, users and passwords stay (the key is not in the data).
# Only a replica set of one member changes : its other members would need the same new key at the same moment. When
# MongoDB does not answer with the new key, the key of before goes back. plan_mongo_key looks (nothing changes), before
# the answers are shown.

# The SHA-256 of that key, as MongoDB reads it (its characters, without spaces and line ends).
readonly V3_PUBLIC_KEY_SHA=a896eb10d78bae1f883638746e9ef688f3f6068934664ee29760ea80609da505
MONGO_KEY='' MONGO_KEY_FILE='' MONGO_KEY_INSIDE='' MONGO_KEY_PORT='' MONGO_KEY_USER='' MONGO_KEY_PASSWORD='' MONGO_KEY_DBS=''
MONGO_KEY_BACKUP='' MONGO_KEY_CHANGED=0

# key_sha FILE : the SHA-256 of a key file, as MongoDB reads it.
key_sha() { tr -d ' \t\r\n' <"$1" | sha256sum | cut -d' ' -f1; }
# cmd_arg CONTAINER FLAG : the value of FLAG in the program of the container ("" : not there).
cmd_arg() {
    try docker inspect -f '{{range .Config.Cmd}}{{println .}}{{end}}' "$1" |
        awk -v k="$2" 'p == k { print; exit } index($0, k "=") == 1 { print substr($0, length(k) + 2); exit } { p = $0 }'
}
# mongo_key_by_hand FILE : how a person gives MongoDB a new key (the file keeps its owner and its mode).
mongo_key_by_hand() {
    printf 'To change it : openssl rand -base64 756 > %s (the same file for every member of the replica set), then docker restart %s.' "$1" "$MONGODB_CONTAINER"
}

plan_mongo_key() {
    MONGO_KEY=''
    [ "$KIND" = PRIMARY ] && [ "$INSTALL_MONGO" = no ] || return 0
    docker inspect "$MONGODB_CONTAINER" >/dev/null 2>&1 || return 0
    local inside file
    inside="$(cmd_arg "$MONGODB_CONTAINER" --keyFile)"
    [ -n "$inside" ] || return 0
    file="$(mount_source "$MONGODB_CONTAINER" "$inside")"
    [ -n "$file" ] && [ -f "$file" ] && [ ! -L "$file" ] || return 0
    [ "$(key_sha "$file")" = "$V3_PUBLIC_KEY_SHA" ] || return 0
    local stays="MongoDB keeps the key of its replica set the installer of v3 wrote on every server, a public key"
    local re='^mongodb://([A-Za-z0-9_]+):([A-Za-z0-9_]+)@(127\.0\.0\.1|localhost):([0-9]+)/'
    if ! [[ "$MONGO_CONNECTION" =~ $re ]]; then
        warn "$stays : API Maker does not reach it on 127.0.0.1 with a user and a password of letters and digits ($ENV_FILE). $(mongo_key_by_hand "$file")"
        return 0
    fi
    local user=${BASH_REMATCH[1]} password=${BASH_REMATCH[2]} port out rs
    port="$(cmd_arg "$MONGODB_CONTAINER" --port)"
    port=${port:-27017}
    if ! is_running "$MONGODB_CONTAINER"; then
        warn "$stays : it does not run now (docker start $MONGODB_CONTAINER, then run the installer again for a new key)."
        return 0
    fi
    out=$(mongo_eval "$MONGODB_CONTAINER" "$port" "$user" "$password" "$MONGO_FACTS_JS" 2>&1 || true)
    rs=$(grep $'^rs\t' <<<"$out" | head -n1 || true)
    if [ -z "$rs" ]; then
        warn "$stays : it does not say what its replica set is ($(tail -n1 <<<"$out" | cut -c1-200)). $(mongo_key_by_hand "$file")"
        return 0
    fi
    if [ "$(cut -f3 <<<"$rs")" != 1 ]; then
        warn "$stays : its replica set has $(cut -f3 <<<"$rs") members, which need the same new key at the same moment. $(mongo_key_by_hand "$file")"
        return 0
    fi
    MONGO_KEY=yes MONGO_KEY_FILE=$file MONGO_KEY_INSIDE=$inside MONGO_KEY_PORT=$port MONGO_KEY_USER=$user MONGO_KEY_PASSWORD=$password
    MONGO_KEY_DBS=$(grep $'^dbs\t' <<<"$out" | head -n1 | cut -f2 || true)
}

# mongo_renew_key : a new random key in the key file (its owner and its mode kept), MongoDB restarted with it, then the
# primary of its replica set again, with every database of before.
mongo_renew_key() {
    local tmp sha out now name
    tmp=$(mktemp "$MONGO_KEY_FILE.new.XXXXXX") || return 1
    openssl rand -base64 756 | tr -d '\n' | fold -w 64 >"$tmp" || return 1
    chown --reference="$MONGO_KEY_FILE" "$tmp" || return 1
    chmod --reference="$MONGO_KEY_FILE" "$tmp" || return 1
    sha=$(key_sha "$tmp")
    [ "$(tr -d ' \t\r\n' <"$tmp" | wc -c)" -ge 1000 ] && [ "$sha" != "$V3_PUBLIC_KEY_SHA" ] || { echo 'the new key was not written'; return 1; }
    MONGO_KEY_CHANGED=1
    mv -f "$tmp" "$MONGO_KEY_FILE" || return 1
    # Docker mounts the file again when the container starts : MongoDB reads the new one.
    docker restart -t 60 "$MONGODB_CONTAINER" || return 1
    if [ "$(docker exec "$MONGODB_CONTAINER" sh -c "tr -d ' \t\r\n' < '$MONGO_KEY_INSIDE' | sha256sum" | cut -d' ' -f1)" != "$sha" ]; then
        echo "MongoDB does not read the new key ($MONGO_KEY_INSIDE in its container)"
        return 1
    fi
    mongo_wait_primary "$MONGODB_CONTAINER" "$MONGO_KEY_PORT" "$MONGO_KEY_USER" "$MONGO_KEY_PASSWORD" || return 1
    out=$(mongo_eval "$MONGODB_CONTAINER" "$MONGO_KEY_PORT" "$MONGO_KEY_USER" "$MONGO_KEY_PASSWORD" "$MONGO_FACTS_JS" 2>&1 || true)
    printf '%s\n' "$out"
    if [ "$(grep $'^rs\t' <<<"$out" | head -n1 | cut -f3)" != 1 ]; then
        echo 'the replica set does not answer with its one member'
        return 1
    fi
    now=",$(grep $'^dbs\t' <<<"$out" | head -n1 | cut -f2 || true),"
    while IFS= read -r name; do
        [ -n "$name" ] || continue
        case "$now" in *",$name,"*) ;; *) echo "the database $name is not there"; return 1 ;; esac
    done < <(tr ',' '\n' <<<"$MONGO_KEY_DBS")
}

# mongo_key_back : the key of before in the key file, MongoDB restarted with it, the primary again.
mongo_key_back() {
    cp -p "$MONGO_KEY_BACKUP" "$MONGO_KEY_FILE.back" || return 1
    mv -f "$MONGO_KEY_FILE.back" "$MONGO_KEY_FILE" || return 1
    docker restart -t 60 "$MONGODB_CONTAINER" || return 1
    mongo_wait_primary "$MONGODB_CONTAINER" "$MONGO_KEY_PORT" "$MONGO_KEY_USER" "$MONGO_KEY_PASSWORD"
}

renew_mongo_key() {
    [ "$MONGO_KEY" = yes ] || return 0
    local stays="MongoDB keeps the key of its replica set the installer of v3 wrote on every server, a public key"
    MONGO_KEY_BACKUP="$MONGO_KEY_FILE.before-new-key.$(date '+%Y-%m-%d_%H-%M-%S')"
    MONGO_KEY_CHANGED=0
    if ! cp -p "$MONGO_KEY_FILE" "$MONGO_KEY_BACKUP"; then
        warn "$stays : its key file could not be copied first. $(mongo_key_by_hand "$MONGO_KEY_FILE")"
        return 0
    fi
    progress_start "MongoDB : a new key for its replica set"
    if mongo_renew_key >>"$INSTALL_LOG" 2>&1; then
        progress_end
        rm -f "$MONGO_KEY_BACKUP"
        ok "MongoDB : a new random key for its replica set, in $MONGO_KEY_FILE (the installer of v3 wrote the same public key on every server)"
        return 0
    fi
    progress_end
    rm -f "$MONGO_KEY_FILE".new.*
    if [ "$MONGO_KEY_CHANGED" = 0 ]; then
        rm -f "$MONGO_KEY_BACKUP"
        warn "$stays : a new key could not be written (the log of the installer says why). $(mongo_key_by_hand "$MONGO_KEY_FILE")"
        return 0
    fi
    printf '\n==== %s : MongoDB : the key of before goes back\n' "$(date '+%F %T')" >>"$INSTALL_LOG"
    if ! mongo_key_back >>"$INSTALL_LOG" 2>&1; then
        fail "MongoDB did not start with a new key for its replica set, nor with the key of before. The key of before : $MONGO_KEY_BACKUP (cp -p it to $MONGO_KEY_FILE, then docker restart $MONGODB_CONTAINER)."
    fi
    rm -f "$MONGO_KEY_BACKUP"
    warn "$stays : MongoDB did not answer with a new key, and runs with the key of before (the log of the installer says why). $(mongo_key_by_hand "$MONGO_KEY_FILE")"
}

ORACLE_FOLDER=/opt/oracle/instantclient

# The Oracle Instant Client : API Maker loads it when an instance of Oracle is used. A failure here is no failure of
# the installation : everything else works without it.
install_oracle_client() {
    if [ -f "$ORACLE_FOLDER/libclntsh.so" ] || ls "$ORACLE_FOLDER"/libclntsh.so* >/dev/null 2>&1; then
        ok "Oracle Instant Client"
        return 0
    fi
    local url=$ORACLE_X64_URL status=0
    [ "$ARCH" = arm64 ] && url=$ORACLE_ARM64_URL
    printf '⏳  Installing the Oracle Instant Client…\n'
    # Its own bash : `set -e` holds there (it does not inside a condition of this script).
    bash -c '
        set -e
        url=$1 folder=$2
        apt-get -o DPkg::Lock::Timeout=600 install -y -q libaio1 || apt-get -o DPkg::Lock::Timeout=600 install -y -q libaio1t64
        # libaio1t64 (Ubuntu 24.04 and newer) has libaio.so.1t64, the client asks for libaio.so.1.
        for found in /usr/lib/*/libaio.so.1t64; do if [ -e "$found" ]; then ln -sf "$found" "$(dirname "$found")/libaio.so.1"; fi; done
        rm -rf /opt/oracle/download
        mkdir -p /opt/oracle/download
        curl -fsSL --retry 3 -o /opt/oracle/download/client.zip "$url"
        unzip -q -o /opt/oracle/download/client.zip -d /opt/oracle/download
        library="$(find /opt/oracle/download -name "libclntsh.so*" | head -1)"
        [ -n "$library" ]
        rm -rf "$folder"
        mv "$(dirname "$library")" "$folder"
        rm -rf /opt/oracle/download
        echo "$folder" >/etc/ld.so.conf.d/oracle-instantclient.conf
        ldconfig
    ' oracle "$url" "$ORACLE_FOLDER" >>"$INSTALL_LOG" 2>&1 || status=$?
    if [ "$status" -ne 0 ]; then
        warn "The Oracle Instant Client could not be installed : instances of Oracle will not connect until it is in $ORACLE_FOLDER (see $INSTALL_LOG)."
        return 0
    fi
    ok "Oracle Instant Client installed in $ORACLE_FOLDER"
}

# ---------------------------------------------------------------------------------------------------- the release

AM_VERSION=''
DOWNLOAD=''
STAGED=''

# The archive of the release : the one --package names, or the npm package of this architecture.
download_release() {
    section "API Maker"
    local work="$APP_ROOT/.download"
    rm -rf "$work"
    mkdir -p "$work"
    if [ -n "$ARG_PACKAGE" ]; then
        case "$ARG_PACKAGE" in
            http://* | https://*)
                run "Downloading $ARG_PACKAGE" curl -fSL --retry 3 -o "$work/release.tgz" "$ARG_PACKAGE"
                if curl -fsSL --retry 2 -o "$work/release.tgz.sha256" "$ARG_PACKAGE.sha256" 2>/dev/null; then
                    check_sha256 "$work/release.tgz" "$work/release.tgz.sha256"
                fi
                ;;
            *)
                [ -f "$ARG_PACKAGE" ] || fail "--package : no file $ARG_PACKAGE"
                cp "$ARG_PACKAGE" "$work/release.tgz"
                [ -f "$ARG_PACKAGE.sha256" ] && check_sha256 "$work/release.tgz" "$ARG_PACKAGE.sha256"
                ;;
        esac
        DOWNLOAD="$work/release.tgz"
        return 0
    fi
    local package="$NPM_SCOPE/api-maker-engine-linux-$ARCH" metadata tarball integrity
    metadata="$work/metadata.json"
    curl -fsSL --retry 3 -H 'Accept: application/json' -o "$metadata" "$NPM_REGISTRY/${package/\//%2f}" \
        || fail "The release of API Maker for linux-$ARCH could not be read from $NPM_REGISTRY ($package)."
    AM_VERSION="$ARG_VERSION"
    [ "$AM_VERSION" = latest ] && AM_VERSION="$(jq -r '."dist-tags".latest // empty' "$metadata")"
    [ -n "$AM_VERSION" ] || fail "$package has no latest version."
    [ "${AM_VERSION%%.*}" = "$AM_MAJOR" ] || warn "Version $AM_VERSION is not a version $AM_MAJOR of API Maker."
    tarball="$(jq -r --arg version "$AM_VERSION" '.versions[$version].dist.tarball // empty' "$metadata")"
    integrity="$(jq -r --arg version "$AM_VERSION" '.versions[$version].dist.integrity // empty' "$metadata")"
    if [ -z "$tarball" ]; then
        fail "API Maker $AM_VERSION is not published for linux-$ARCH. Published : $(jq -r '.versions | keys | join(", ")' "$metadata")"
    fi
    run "Downloading API Maker $AM_VERSION (linux-$ARCH)" curl -fSL --retry 3 -o "$work/release.tgz" "$tarball"
    if [ -n "$integrity" ]; then
        local algorithm=${integrity%%-*} actual
        actual="$algorithm-$(openssl dgst "-$algorithm" -binary "$work/release.tgz" | openssl base64 -A)"
        [ "$actual" = "$integrity" ] || fail "The download of API Maker $AM_VERSION is damaged : its $algorithm is not the one of npm. Run the installer again."
        ok "Checked : $algorithm of the download"
    fi
    DOWNLOAD="$work/release.tgz"
}

check_sha256() {
    local file=$1 sums=$2 wanted actual
    wanted="$(awk '{print $1; exit}' "$sums")"
    actual="$(sha256sum "$file" | awk '{print $1}')"
    [ "$wanted" = "$actual" ] || fail "The release archive is damaged : its SHA-256 is not the one of $(basename "$sums")."
    ok "Checked : SHA-256 of the release archive"
}

# Unpacks the release next to the others and checks it runs here, before anything else changes.
stage_release() {
    local work="$APP_ROOT/.download/unpacked" found machine expected
    rm -rf "$work"
    mkdir -p "$work"
    tar --warning=no-unknown-keyword -xzf "$DOWNLOAD" -C "$work" || fail "The release archive can not be unpacked."
    found="$(find "$work" -maxdepth 3 -type f -name api_maker_be | head -1)"
    [ -n "$found" ] || fail "The release archive holds no api_maker_be."
    found="$(dirname "$found")"
    [ -f "$found/am_agent" ] || fail "The release archive holds no am_agent (the program of the sandboxes)."
    local packaged
    packaged="$(tr -d '[:space:]' <"$found/VERSION" 2>/dev/null || true)"
    [ -n "$packaged" ] || fail "The release archive has no VERSION."
    if [ -n "$AM_VERSION" ] && [ "$AM_VERSION" != "$packaged" ]; then fail "The archive is version $packaged, $AM_VERSION was asked."; fi
    AM_VERSION=$packaged
    # The kind of machine the program is for (e_machine of its ELF header) : x86-64 is 3e, AArch64 b7.
    machine="$(od -An -tx1 -j18 -N1 "$found/api_maker_be" | tr -d ' ')"
    case "$ARCH" in x64) expected=3e ;; arm64) expected=b7 ;; esac
    [ "$machine" = "$expected" ] || fail "The release is for another processor than this $(uname -m) server."
    chmod 755 "$found/api_maker_be" "$found/am_agent"
    local said
    said="$("$found/api_maker_be" --version 2>&1)" || fail "api_maker_be $AM_VERSION does not start on this server : $said"
    [ "$said" = "api_maker_be $AM_VERSION" ] || warn "api_maker_be says '$said'."
    ok "API Maker $AM_VERSION runs on this server"
    STAGED="$RELEASES/$AM_VERSION"
    if [ "$(readlink -f "$CURRENT" 2>/dev/null)" = "$(readlink -f "$STAGED" 2>/dev/null)" ] && [ -e "$STAGED" ]; then
        # The version which runs is installed again : the files of the program are replaced while it is stopped.
        STAGED="$RELEASES/$AM_VERSION.new"
    fi
    rm -rf "$STAGED"
    mv "$found" "$STAGED"
    rm -rf "$APP_ROOT/.download"
}

# The uploaded files and the license of the Node.js edition come with it.
carry_over_old_files() {
    [ "$OLD_EDITION" = 1 ] || return 0
    if [ -d "$OLD_APP_ROOT/uploads" ] && [ -z "$(ls -A "$APP_ROOT/uploads" 2>/dev/null)" ]; then
        cp -a "$OLD_APP_ROOT/uploads/." "$APP_ROOT/uploads/" && ok "The uploaded files of the Node.js edition copied to $APP_ROOT/uploads"
    fi
    if [ -f "$OLD_APP_ROOT/license.txt" ] && [ ! -f "$APP_ROOT/license.txt" ]; then
        cp "$OLD_APP_ROOT/license.txt" "$APP_ROOT/license.txt" && ok "The license file of the Node.js edition copied"
    fi
}

get_license() {
    [ -n "$ARG_LICENSE_KEY" ] || return 0
    local answer data
    answer="$(curl -fsS --retry 2 -H 'Content-Type: application/json' \
        -d "$(jq -cn --arg key "$ARG_LICENSE_KEY" '{ t: "hKfIVfndQjOLBGJqoAIPtsXFAzQ_p_tkn", key: $key }')" "$LICENSE_CORE_URL" 2>/dev/null || true)"
    data="$(jq -r '.data // empty' <<<"$answer" 2>/dev/null || true)"
    [ -n "$data" ] || fail "The license key was not found."
    printf '%s' "$data" >"$APP_ROOT/license.txt"
    chmod 600 "$APP_ROOT/license.txt"
    ok "License file written : $APP_ROOT/license.txt"
}

reset_license_mac_address() {
    [ -n "$ARG_LICENSE_KEY" ] || return 0
    if curl -fsS --retry 2 -H 'Content-Type: application/json' \
        -d "$(jq -cn --arg key "$ARG_LICENSE_KEY" '{ t: "DhZmRN2JzSgndq_J5f4d_p_tkn", key: $key }')" "$LICENSE_RESET_URL" >/dev/null 2>&1; then
        ok "The MAC address of this server is registered for the license."
    else
        warn "The MAC address could not be registered for the license : do it from the admin panel (Root settings)."
    fi
}

# ---------------------------------------------------------------------------------------------------- settings

API_URL=''
WS_URL=''
PANEL_URL=''

work_out_urls() {
    # API Maker's built-in web server : HTTPS on the IP address serves everything there; a secondary server is reached
    # through its primary server, and on its own port.
    if [ "$PROXY" = builtin ] && [ "$HTTPS_ON_IP" = yes ]; then
        API_URL="https://$SERVER_IP"
        WS_URL="wss://$SERVER_IP"
        [ "$KIND" = PRIMARY ] && PANEL_URL="https://$SERVER_IP"
        return 0
    fi
    if [ "$PROXY" = builtin ] && [ "$KIND" = SECONDARY ]; then
        API_URL="http://$SERVER_IP:$API_PORT"
        WS_URL="ws://$SERVER_IP:$API_PORT"
        return 0
    fi
    if [ "$INSTALL_CADDY" = yes ] || [ "$PROXY" = builtin ]; then
        if [ "$INSTALL_SSL" = yes ]; then
            API_URL="https://$API_DOMAIN"
            WS_URL="wss://$WS_DOMAIN"
            [ "$KIND" = PRIMARY ] && PANEL_URL="https://$PANEL_DOMAIN"
        else
            API_URL="http://$SERVER_IP:$CADDY_API_PORT"
            WS_URL="ws://$SERVER_IP:$CADDY_WS_PORT"
            [ "$KIND" = PRIMARY ] && PANEL_URL="http://$SERVER_IP"
        fi
    else
        API_URL="http://$SERVER_IP:$API_PORT"
        WS_URL="ws://$SERVER_IP:$API_PORT"
        [ "$KIND" = PRIMARY ] && PANEL_URL="http://$SERVER_IP:$PANEL_PORT"
    fi
    return 0
}

# The keys the installer writes, and the ones API Maker v4 has no use for (of the Node.js edition, or of an earlier
# version of v4) : the others of an earlier .env are kept as they were.
readonly WRITTEN_KEYS=" BE_HOST_PORT am__serverName am__logFilePath am__port am__adminPanel__port am__adminPanel__folder am__oracleClientPath am__mongo_db_connection am__redisInternal am__redisExternal am__passCommunication am__passJWT am__passDBEncryptDecrypt "
readonly DROPPED_KEYS=" NODE_PRESERVE_SYMLINKS NODE_ENV BE_WS_HOST_PORT am__wsPort am__cpuCount am__workerThreads am__processTitle "

write_env() {
    if [ -f "$ENV_FILE" ]; then
        local backup
        backup="$CONFIG/bkp_env/.env__$(date '+%d_%m_%Y__%H_%M_%S')"
        cp "$ENV_FILE" "$backup"
        chmod 600 "$backup"
        ok "Backup of the settings : $backup"
    fi
    local kept=() line key
    if [ -f "$ENV_FILE" ]; then
        while IFS= read -r line || [ -n "$line" ]; do
            [[ "$line" =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)= ]] || continue
            key="${BASH_REMATCH[2]}"
            [[ "$WRITTEN_KEYS" == *" $key "* ]] && continue
            [[ "$DROPPED_KEYS" == *" $key "* ]] && continue
            kept+=("$line")
        done <"$ENV_FILE"
    fi
    local panel_lines=''
    if [ "$KIND" = PRIMARY ]; then
        panel_lines="am__adminPanel__folder=\"$CURRENT/admin-panel\" # API Maker serves its admin panel from this folder…
am__adminPanel__port=$PANEL_PORT # …on this port"
    fi
    local external=''
    [ -n "$REDIS_EXTERNAL" ] && external="am__redisExternal='$REDIS_EXTERNAL'"
    umask 077
    cat >"$ENV_FILE" <<EOF
# The settings of API Maker v4 (api_maker_be_rust), written by its installer : they override the defaults of the "am"
# settings ("__" goes into an object : am__logs__enableLogs=false is am.logs.enableLogs). The installer keeps the lines
# it does not write. Restart API Maker after a change : systemctl restart $SERVICE

# Where the admin panel (and the browsers of your users) reach API Maker : its web sockets too, ws:// or wss://.
BE_HOST_PORT="$API_URL" # 👈 http://127.0.0.1:$DEFAULT_API_PORT or https://example.com

am__serverName=$SERVER_NAME
am__logFilePath=$LOG_FILE
am__port=$API_PORT # the APIs and the web sockets
$panel_lines
am__oracleClientPath=$ORACLE_FOLDER
am__mongo_db_connection="$MONGO_CONNECTION"
am__redisInternal='$REDIS_INTERNAL'
$external
am__passCommunication="$PASS_COMMUNICATION"
am__passJWT="$PASS_JWT"
am__passDBEncryptDecrypt="$PASS_DB" # 👈 32 characters : the data of the databases and of the git repositories is encrypted with it.
EOF
    if [ "${#kept[@]}" -gt 0 ]; then
        printf '\n# Kept from the earlier settings.\n' >>"$ENV_FILE"
        printf '%s\n' "${kept[@]}" >>"$ENV_FILE"
    fi
    umask 022
    chmod 600 "$ENV_FILE"
    ok "Settings written : $ENV_FILE"
}

# ---------------------------------------------------------------------------------------------------- systemd

# A word of a command line of systemd : % and $ are its own, a word with a space is quoted.
systemd_word() {
    local word=${1//%/%%}
    word=${word//\$/\$\$}
    if [[ "$word" =~ [[:space:]\"\'\\] ]]; then
        word=${word//\\/\\\\}
        word=${word//\"/\\\"}
        printf '"%s"' "$word"
    else
        printf '%s' "$word"
    fi
}

write_services() {
    local start
    start="$(systemd_word "$CURRENT/api_maker_be") $(systemd_word "--appRoot=$APP_ROOT") $(systemd_word "--envPath=$ENV_FILE")"
    local back_off=''
    [ "$SYSTEMD_VERSION" -ge 254 ] && back_off="# After each crash in a row it waits a bit longer, up to 30 seconds.
RestartSteps=10
RestartMaxDelaySec=30s"
    cat >"$SYSTEMD_DIR/$SERVICE.service" <<EOF
# Written by the API Maker installer : API Maker v4, run by systemd. It starts when the server boots and again whenever
# it stops; what it prints goes to $LOG_FILE. The installer writes this file again every time it runs : the settings of
# API Maker are in $ENV_FILE.

[Unit]
Description=API Maker
Documentation=https://docs.apimaker.dev
Wants=network-online.target
After=network-online.target docker.service
# It never gives up : a database which is down for a while must not leave API Maker stopped.
StartLimitIntervalSec=0

[Service]
Type=exec
User=root
WorkingDirectory=$APP_ROOT
EnvironmentFile=$SERVICE_FOLDER/$SERVICE.env
# One process : the APIs, the web sockets and the admin panel, on every core of the server.
ExecStart=$start
StandardOutput=append:$LOG_FILE
StandardError=append:$LOG_FILE
Restart=always
RestartSec=1s
$back_off
# SIGTERM : the requests in flight finish, the clients of the web sockets are taken out of Redis and closed, the logs
# are written, the schedulers go to the other servers. The process gives that a minute at the most : it is killed
# after 90 seconds.
KillMode=mixed
TimeoutStopSec=90s
# Every client of the web sockets is an open file : as many as the firewall of the machine tracks (the installer).
LimitNOFILE=$OPEN_FILES
LimitNPROC=infinity

[Install]
WantedBy=multi-user.target
EOF
    # The language and time zone of the shell the installer runs in go with API Maker : dates and numbers stay what
    # they were for code that formats them.
    {
        echo "# Written by the API Maker installer : the environment of $SERVICE.service. The settings of API Maker are in $ENV_FILE."
        echo "HOME=\"$HOME_DIR\""
        echo "PATH=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\""
        local name
        for name in LANG LANGUAGE LC_ALL LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES TZ; do
            [ -n "${!name:-}" ] && printf '%s="%s"\n' "$name" "${!name//\"/}"
        done
    } >"$SERVICE_FOLDER/$SERVICE.env"
    chmod 600 "$SERVICE_FOLDER/$SERVICE.env"

    local logrotate
    logrotate="$(command -v logrotate || echo /usr/sbin/logrotate)"
    cat >"$SERVICE_FOLDER/logrotate.conf" <<EOF
# Written by the API Maker installer : the log of API Maker is rotated past 50 MB, the last 10 are kept compressed.
# systemd keeps it open : it is copied, then emptied (copytruncate).
$LOG_FILE {
    size 50M
    rotate 10
    compress
    copytruncate
    missingok
    notifempty
    su root root
}
EOF
    cat >"$SYSTEMD_DIR/$LOGROTATE_SERVICE.service" <<EOF
# Written by the API Maker installer : rotates the log of API Maker, run by $LOGROTATE_SERVICE.timer.

[Unit]
Description=Rotate the log of API Maker

[Service]
Type=oneshot
ExecStart=$logrotate --state $SERVICE_FOLDER/logrotate.status $SERVICE_FOLDER/logrotate.conf
EOF
    cat >"$SYSTEMD_DIR/$LOGROTATE_SERVICE.timer" <<EOF
# Written by the API Maker installer : checks the size of the log of API Maker every 5 minutes.

[Unit]
Description=Rotate the log of API Maker

[Timer]
OnCalendar=*:0/5
AccuracySec=30s

[Install]
WantedBy=timers.target
EOF
    # The server of the admin panel of the Node.js edition : API Maker serves the panel itself now.
    if [ -f "$SYSTEMD_DIR/$OLD_PANEL_SERVICE.service" ]; then
        try systemctl disable --quiet --now "$OLD_PANEL_SERVICE"
        rm -f "$SYSTEMD_DIR/$OLD_PANEL_SERVICE.service" "$SERVICE_FOLDER/admin-panel-server.js"
        ok "The admin panel server of the Node.js edition removed : API Maker serves the panel itself"
    fi
    rm -f "$SERVICE_FOLDER/log-time.js" # API Maker v4 dates every line itself.
    systemctl daemon-reload
    systemctl enable --quiet "$SERVICE"
    systemctl enable --quiet --now "$LOGROTATE_SERVICE.timer"
}

# Points `current` at the new version, all at once.
switch_to() {
    local target=$1
    if [[ "$target" == *.new ]]; then
        local final="${target%.new}"
        rm -rf "$final.old"
        [ -e "$final" ] && mv "$final" "$final.old"
        mv "$target" "$final"
        rm -rf "$final.old"
        target=$final
    fi
    ln -sfn "$target" "$CURRENT.next"
    mv -T "$CURRENT.next" "$CURRENT"
}

# Waits for API Maker to answer on its port (its page at /), and for its admin panel.
wait_until_up() {
    local seconds=${1:-120} waited=0
    while [ "$waited" -lt "$seconds" ]; do
        if curl -fsS -o /dev/null --max-time 3 "http://127.0.0.1:$API_PORT/" 2>/dev/null; then
            if [ "$KIND" = SECONDARY ] || curl -fsS -o /dev/null --max-time 3 "http://127.0.0.1:$PANEL_PORT/" 2>/dev/null; then
                return 0
            fi
        fi
        if ! systemctl is-active --quiet "$SERVICE" && [ "$waited" -gt 10 ] && [ "$(systemctl show -p NRestarts --value "$SERVICE")" -gt 3 ]; then
            return 1
        fi
        sleep 2
        waited=$((waited + 2))
    done
    return 1
}

start_api_maker() {
    local previous=''
    previous="$(readlink -f "$CURRENT" 2>/dev/null || true)"
    switch_to "$STAGED"
    # From here, a version which does not start is rolled back (below), not started again as it was.
    WAS_RUNNING=0
    : >"$LOG_FILE"
    if ! run "Starting API Maker $AM_VERSION" systemctl restart "$SERVICE"; then return 1; fi
    if wait_until_up 150; then
        ok "API Maker $AM_VERSION answers on port $API_PORT"
        return 0
    fi
    printf '%s❌  API Maker %s did not start. The end of its log :%s\n' "$C_RED" "$AM_VERSION" "$C_OFF" >&2
    tail -n 40 "$LOG_FILE" 2>/dev/null | sed 's/^/    /' >&2
    if [ -n "$previous" ] && [ -x "$previous/api_maker_be" ] && [ "$previous" != "$(readlink -f "$CURRENT")" ]; then
        warn "Going back to the version which ran before : $(basename "$previous")"
        ln -sfn "$previous" "$CURRENT.next"
        mv -T "$CURRENT.next" "$CURRENT"
        systemctl restart "$SERVICE" || true
        if wait_until_up 120; then ok "API Maker $(basename "$previous") runs again."; else warn "The earlier version does not answer either."; fi
        rm -rf "$STAGED" "${STAGED%.new}"
    fi
    fail "API Maker $AM_VERSION did not start : systemctl status $SERVICE ; tail -n 100 $LOG_FILE"
}

prune_releases() {
    local running
    running="$(readlink -f "$CURRENT")"
    local old
    # The newest first : the running one and the ones before it are kept.
    for old in $(ls -1dt "$RELEASES"/*/ 2>/dev/null | sed 's#/$##' | tail -n +$((KEEP_RELEASES + 1))); do
        [ "$(readlink -f "$old")" = "$running" ] && continue
        rm -rf "$old"
    done
}

# ---------------------------------------------------------------------------------------------------- the built-in web server

EDGE_REVISION=''
EDGE_TURNED_OFF=0 # this run turned the built-in web server off for another web server : it comes back on failure
EDGE_BACKUP=''    # edge.json as it was before this run
CADDY_STOPPED=0   # Caddy gave its ports to the built-in web server in this run

# The kernel encrypts the connections once their TLS handshake is over (kernel TLS) : its module, now and at every boot.
load_tls_module() {
    if [ "$IN_CONTAINER" = 1 ]; then
        note "This server is a container : the kernel of its host decides whether kernel TLS is there."
        return 0
    fi
    if [ -d /sys/module/tls ] || modprobe tls >/dev/null 2>&1; then
        ok "Kernel TLS : the module of the kernel is loaded"
    else
        warn "The kernel has no TLS module : the built-in web server encrypts in API Maker itself (slower)."
    fi
    [ "$(cat "$MODULES_FILE" 2>/dev/null || true)" = tls ] || echo tls >"$MODULES_FILE"
}

# The servers an earlier Caddyfile spread the requests over besides this one (secondary servers) : address:port, one by line.
caddy_others() {
    [ -f "$CADDYFILE" ] || return 0
    local old_port
    old_port="$(old am__port)"
    grep -E "reverse_proxy 127\.0\.0\.1:(${old_port:-$API_PORT}|$API_PORT)( |$)" "$CADDYFILE" | head -1 | sed -E 's/.*reverse_proxy 127\.0\.0\.1:[0-9]+//' | xargs -n1 2>/dev/null || true
}

# The settings of the built-in web server, written before API Maker starts (it reads them as it starts, and whenever
# they change). Checked by the program of the version about to start first. With another web server, a built-in web
# server that was on is turned off : its ports go to Caddy, or to nobody.
write_edge() {
    if [ "$PROXY" != builtin ]; then
        edge_off
        return 0
    fi
    section "API Maker's built-in web server"
    mkdir -p "$EDGE_DIR/backups" "$LOGS/edge"
    chmod 700 "$EDGE_DIR"
    load_tls_module
    local program="$STAGED/api_maker_be"
    case "$(try "$program" --help)" in
        *"edge check"*) ;;
        *) fail "API Maker $AM_VERSION has no built-in web server : choose a newer version, or --proxy=caddy." ;;
    esac
    if [ -f "$EDGE_FILE" ]; then
        EDGE_BACKUP="$EDGE_DIR/backups/edge.json__$(date '+%Y%m%d_%H%M%S')"
        cp -p "$EDGE_FILE" "$EDGE_BACKUP"
    fi
    if [ "$EDGE_KEEP" = yes ]; then
        EDGE_REVISION="$(try jq -r '.revision // ""' "$EDGE_FILE")"
        ok "The settings of the admin panel stay : $EDGE_FILE"
        return 0
    fi
    local mode=ip admin='' api='' ws='' https_ip=false public='[]' from='[]' imports='[]' servers
    if [ "$KIND" = SECONDARY ]; then
        mode=off
        from="[\"$PRIMARY_IP\"]"
    elif [ "$INSTALL_SSL" = yes ] && [ "$PANEL_DOMAIN" = "$API_DOMAIN" ] && [ "$API_DOMAIN" = "$WS_DOMAIN" ]; then
        mode=oneDomain admin=$PANEL_DOMAIN
    elif [ "$INSTALL_SSL" = yes ]; then
        mode=domains admin=$PANEL_DOMAIN api=$API_DOMAIN ws=$WS_DOMAIN
    elif [ "$HTTPS_ON_IP" = yes ]; then
        https_ip=true public="[\"$SERVER_IP\"]"
    fi
    # The other API Maker servers of an earlier gateway stay : those of edge.json, else those of an earlier Caddyfile.
    servers="$(try jq -c '.apiMaker.gateway.servers // []' "$EDGE_FILE")"
    if [ -z "$servers" ] || [ "$servers" = '[]' ]; then
        servers="$(caddy_others | jq -R -s -c 'split("\n") | map(select(length > 0))')"
    fi
    # The certificates of a Caddy that ran here : API Maker takes those valid for more than 7 days (no new order).
    [ -d "$HOME_DIR/.local/share/caddy/certificates" ] && imports="[\"$HOME_DIR/.local/share/caddy\"]"
    local body
    body="$(jq -n --arg mode "$mode" --arg admin "$admin" --arg api "$api" --arg ws "$ws" --argjson httpsIp "$https_ip" --argjson public "$public" \
        --argjson servers "${servers:-[]}" --argjson imports "$imports" --argjson from "$from" --arg log "$LOGS/edge/access.log" '
        {enabled: true, revision: "", managedBy: "installer",
         apiMaker: ({mode: $mode}
            + (if $admin != "" then {adminDomain: $admin} else {} end)
            + (if $api != "" then {apiDomain: $api, wsDomain: $ws} else {} end)
            + (if $httpsIp then {httpsOnIp: true, publicAddresses: $public} else {} end)
            + (if ($servers | length) > 0 and $mode != "off" then {gateway: {servers: $servers, thisServer: true, policy: "least_conn"}} else {} end)),
         tls: {importCertificates: $imports},
         acceptProxyProtocolFrom: $from,
         accessLog: {file: $log}}')"
    EDGE_REVISION="in-$(printf '%s' "$body" | sha256sum | cut -c1-16)"
    # Checked with its sites (the admin panel may have some) by the program about to start, in a folder of its own.
    local check
    check="$(mktemp -d)"
    jq --arg r "$EDGE_REVISION" '.revision = $r' <<<"$body" >"$check/edge.json"
    [ -d "$EDGE_DIR/sites" ] && cp -a "$EDGE_DIR/sites" "$check/"
    local said
    if ! said="$("$program" edge check --envPath="$ENV_FILE" --appRoot="$APP_ROOT" --folder="$check" 2>&1)"; then
        rm -rf "$check"
        printf '%s\n' "$said" | sed 's/^/    /' >&2
        fail "API Maker refuses these settings of its built-in web server."
    fi
    install -m 600 "$check/edge.json" "$EDGE_FILE"
    rm -rf "$check"
    local how=$mode
    [ "$https_ip" = true ] && how="$mode, HTTPS on the address"
    ok "Settings of the built-in web server written : $EDGE_FILE ($how)"
    [ "$servers" != '[]' ] && [ "$mode" != off ] && ok "Other API Maker servers it shares the connections with : $(jq -r 'join(", ")' <<<"$servers")"
    return 0
}

# The built-in web server goes off : its ports are free once API Maker reads edge.json (API Maker is stopped while the
# installer runs : it starts without them).
edge_off() {
    [ -f "$EDGE_FILE" ] && [ "$(try jq -r '.enabled // false' "$EDGE_FILE")" = true ] || return 0
    EDGE_BACKUP="$EDGE_DIR/backups/edge.json__$(date '+%Y%m%d_%H%M%S')"
    mkdir -p "$EDGE_DIR/backups"
    cp -p "$EDGE_FILE" "$EDGE_BACKUP"
    jq --arg r "off-$(date '+%Y%m%d%H%M%S')" '.enabled = false | .revision = $r' "$EDGE_BACKUP" >"$EDGE_FILE.new"
    chmod 600 "$EDGE_FILE.new"
    mv -f "$EDGE_FILE.new" "$EDGE_FILE"
    EDGE_TURNED_OFF=1
    ok "API Maker's built-in web server is turned off (its settings stay : $EDGE_FILE)"
}

# Once API Maker runs : Caddy gives its ports, API Maker takes them within two seconds, then the installer waits until
# API Maker says it runs these settings, and checks API Maker through them. When it does not, Caddy comes back.
finish_edge() {
    [ "$PROXY" = builtin ] || return 0
    if systemctl is-active --quiet caddy 2>/dev/null || systemctl is-enabled --quiet caddy 2>/dev/null; then
        try systemctl disable --quiet --now caddy
        CADDY_STOPPED=1
        ok "Caddy stopped and disabled : the built-in web server takes its ports (its Caddyfile stays : $CADDYFILE)"
    fi
    local waited=0 applied='' failed='' waiting=''
    printf '⏳  Waiting for API Maker to apply the settings of its built-in web server…\n'
    while [ "$waited" -lt 60 ]; do
        applied="$(try jq -r '.appliedRevision // ""' "$EDGE_STATUS")"
        failed="$(try jq -r '.failedRevision // ""' "$EDGE_STATUS")"
        waiting="$(try jq -r '[.listeners[]? | select(.state != "listening") | "\(.port) (\(.error))"] | join(", ")' "$EDGE_STATUS")"
        [ -n "$EDGE_REVISION" ] && [ "$failed" = "$EDGE_REVISION" ] && break
        # (settings the admin panel kept may have no revision : API Maker then names them by a hash of the files)
        [ -z "$EDGE_REVISION" ] && [ "$(try jq -r '.running' "$EDGE_STATUS")" = true ] && EDGE_REVISION=$applied
        [ "$applied" = "$EDGE_REVISION" ] && [ -z "$waiting" ] && break
        sleep 2
        waited=$((waited + 2))
    done
    if [ "$applied" != "$EDGE_REVISION" ] || [ -n "$waiting" ]; then
        local why="API Maker did not apply the settings of its built-in web server in 60 seconds"
        [ "$failed" = "$EDGE_REVISION" ] && why="API Maker refused the settings of its built-in web server : $(try jq -r '[.problems[]? | "\(.file) \(.at) : \(.message)"] | join("; ")' "$EDGE_STATUS")"
        [ "$applied" = "$EDGE_REVISION" ] && [ -n "$waiting" ] && why="The built-in web server waits for port(s) $waiting : another program holds them"
        edge_gives_back
        fail "$why"
    fi
    ok "API Maker's built-in web server runs ($EDGE_REVISION)"
    if [ "$(try jq -r '.kernelTls.on' "$EDGE_STATUS")" = true ]; then
        ok "Kernel TLS : the kernel encrypts the connections"
    elif [ -n "$(try jq -r '.kernelTls.reason // ""' "$EDGE_STATUS")" ] && { [ "$INSTALL_SSL" = yes ] || [ "$HTTPS_ON_IP" = yes ]; }; then
        warn "Kernel TLS is off : $(try jq -r '.kernelTls.reason' "$EDGE_STATUS")"
    fi
    # Its certificates : a certificate still being ordered is a warning (90 seconds for them all).
    local d state tries=45
    for d in $( [ "$INSTALL_SSL" = yes ] && printf '%s\n' "$PANEL_DOMAIN" "$API_DOMAIN" "$WS_DOMAIN" | sort -u ); do
        while :; do
            state="$(try jq -r --arg d "$d" '[.certificates[]? | select(.names | index($d))] | first | .state // ""' "$EDGE_STATUS")"
            case "$state" in valid | expiring) break ;; esac
            [ "$tries" -le 0 ] && break
            tries=$((tries - 1))
            sleep 2
        done
        case "$state" in
            valid | expiring) ok "Certificate of $d" ;;
            *) warn "The certificate of $d is not issued yet (${state:-not ordered yet}) : HTTPS on $d answers once it is. The Web Server page of the admin panel follows it." ;;
        esac
    done
    # API Maker through it.
    if [ "$KIND" = PRIMARY ] && [ "$INSTALL_SSL" = no ] && [ "$HTTPS_ON_IP" = no ]; then
        curl -fsS -o /dev/null --max-time 5 "http://127.0.0.1:$CADDY_API_PORT/" && ok "API Maker answers through it on port $CADDY_API_PORT" ||
            warn "API Maker does not answer on port $CADDY_API_PORT yet"
    fi
    return 0
}

# The built-in web server did not take the ports : it goes off, and Caddy comes back when it ran.
edge_gives_back() {
    if [ -f "$EDGE_FILE" ]; then
        jq --arg r "off-$(date '+%Y%m%d%H%M%S')" '.enabled = false | .revision = $r' "$EDGE_FILE" >"$EDGE_FILE.new" && mv -f "$EDGE_FILE.new" "$EDGE_FILE" || true
        chmod 600 "$EDGE_FILE" 2>/dev/null || true
    fi
    if [ "$CADDY_STOPPED" = 1 ]; then
        sleep 3 # (API Maker reads the change within two seconds and gives the ports back)
        systemctl enable --quiet --now caddy && warn "Caddy runs again, as it was : the built-in web server is off." || true
        CADDY_STOPPED=0
    fi
}

# ---------------------------------------------------------------------------------------------------- Caddy

install_caddy() {
    [ "$INSTALL_CADDY" = yes ] || return 0
    section "Caddy"
    if ! command -v caddy >/dev/null; then
        local version=$CADDY_VERSION found
        found="$(curl -fsS --max-time 10 https://api.github.com/repos/caddyserver/caddy/releases/latest 2>/dev/null | jq -r '.tag_name // empty' 2>/dev/null || true)"
        [[ "$found" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && version="${found#v}"
        local arch=amd64 base
        [ "$ARCH" = arm64 ] && arch=arm64
        base="https://github.com/caddyserver/caddy/releases/download/v$version"
        printf '⏳  Installing Caddy %s…\n' "$version"
        local status=0
        # The release of Caddy itself, checked against its SHA-512 : the same on every Ubuntu.
        bash -c '
            set -e
            base=$1 version=$2 arch=$3
            work=$(mktemp -d)
            cd "$work"
            curl -fsSL --retry 3 -o caddy.tar.gz "$base/caddy_${version}_linux_$arch.tar.gz"
            curl -fsSL --retry 3 -o checksums.txt "$base/caddy_${version}_checksums.txt"
            wanted=$(grep " caddy_${version}_linux_$arch.tar.gz$" checksums.txt | awk "{print \$1}")
            [ -n "$wanted" ] && [ "$(sha512sum caddy.tar.gz | awk "{print \$1}")" = "$wanted" ]
            tar -xzf caddy.tar.gz caddy
            install -m 755 caddy /usr/bin/caddy
            cd /
            rm -rf "$work"
        ' caddy "$base" "$version" "$arch" >>"$INSTALL_LOG" 2>&1 || status=$?
        if [ "$status" -ne 0 ]; then
            # Else the package of Ubuntu.
            apt-get -o DPkg::Lock::Timeout=600 install -y -q caddy >>"$INSTALL_LOG" 2>&1 || true
        fi
        command -v caddy >/dev/null || fail "Caddy could not be installed (see $INSTALL_LOG). Run the installer again, or with --caddy=no."
    fi
    ok "$(caddy version | awk '{print "Caddy " $1}')"
    write_caddyfile
    # Caddy, run by systemd with this Caddyfile : it starts with the server again after a reboot.
    if [ -f /lib/systemd/system/caddy.service ] || [ -f /usr/lib/systemd/system/caddy.service ]; then
        mkdir -p "$SYSTEMD_DIR/caddy.service.d"
        cat >"$SYSTEMD_DIR/caddy.service.d/api-maker.conf" <<EOF
# Written by the API Maker installer : Caddy serves $CADDYFILE.
[Service]
User=root
Group=root
ExecStart=
ExecStart=$(command -v caddy) run --environ --config $CADDYFILE --adapter caddyfile
ExecReload=
# Two open files for every client it passes on to API Maker.
LimitNOFILE=$CADDY_OPEN_FILES
EOF
    else
        cat >"$SYSTEMD_DIR/caddy.service" <<EOF
# Written by the API Maker installer : Caddy in front of API Maker, with $CADDYFILE.
[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
User=root
Group=root
ExecStart=$(command -v caddy) run --environ --config $CADDYFILE --adapter caddyfile
TimeoutStopSec=5s
# Two open files for every client it passes on to API Maker.
LimitNOFILE=$CADDY_OPEN_FILES
Restart=always
RestartSec=2s
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF
    fi
    # A Caddy started by hand (the installer of the Node.js edition did so) holds the ports : it goes.
    try caddy stop >/dev/null
    try pkill -x caddy
    sleep 1
    if ! port_is_free 80 && ! systemctl is-active --quiet caddy; then
        fail "Port 80 is taken by $(ss -ltnpH '( sport = :80 )' | grep -oE 'users:\(\("[^"]+' | sed 's/.*"//' | head -1) : stop it, or run the installer with --caddy=no."
    fi
    systemctl daemon-reload
    systemctl enable --quiet caddy
    run "Starting Caddy" systemctl restart caddy
    # (it has the ports : the built-in web server stays off)
    EDGE_TURNED_OFF=0
}

write_caddyfile() {
    if [ -f "$CADDYFILE" ]; then
        local backup
        backup="$CONFIG/bkp_caddyfile/Caddyfile__$(date '+%d_%m_%Y__%H_%M_%S')"
        cp "$CADDYFILE" "$backup"
        ok "Backup of the Caddyfile : $backup"
    fi
    # The servers an earlier Caddyfile spread the requests over besides this one (secondary servers) stay.
    local others=''
    if [ -f "$CADDYFILE" ]; then
        local old_port
        old_port="$(old am__port)"
        others="$(grep -E "reverse_proxy 127\.0\.0\.1:(${old_port:-$API_PORT}|$API_PORT)( |$)" "$CADDYFILE" | head -1 | sed -E 's/.*reverse_proxy 127\.0\.0\.1:[0-9]+//' | xargs || true)"
    fi
    local api_site ws_site panel_site
    if [ "$INSTALL_SSL" = yes ]; then
        api_site="$API_DOMAIN"
        ws_site="$WS_DOMAIN"
        panel_site="$PANEL_DOMAIN"
    else
        api_site=":$CADDY_API_PORT"
        ws_site=":$CADDY_WS_PORT"
        panel_site=":80"
    fi
    {
        cat <<EOF
# Written by the API Maker installer, again every time it runs (the earlier one is in $CONFIG/bkp_caddyfile).
# The APIs and the web sockets are one port of API Maker ($API_PORT); the admin panel is its port $PANEL_PORT.
{
    admin off
    log {
        level ERROR
        output discard
    }
}

$api_site {
    reverse_proxy 127.0.0.1:$API_PORT${others:+ $others}
}
EOF
        if [ "$ws_site" != "$api_site" ]; then
            cat <<EOF

$ws_site {
    reverse_proxy 127.0.0.1:$API_PORT${others:+ $others}
}
EOF
        fi
        if [ "$KIND" = PRIMARY ]; then
            cat <<EOF

$panel_site {
    reverse_proxy 127.0.0.1:$PANEL_PORT
}
EOF
        fi
    } >"$CADDYFILE"
    if ! caddy validate --config "$CADDYFILE" --adapter caddyfile >>"$INSTALL_LOG" 2>&1; then
        fail "The Caddyfile written to $CADDYFILE is not valid : see $INSTALL_LOG"
    fi
    ok "Caddyfile written : $CADDYFILE"
    [ -n "$others" ] && ok "Secondary servers kept in the Caddyfile : $others"
    return 0
}

# ---------------------------------------------------------------------------------------------------- the end

print_summary() {
    section "API Maker, run by systemd"
    local state restarts pid enabled
    state="$(systemctl show -p ActiveState --value "$SERVICE") ($(systemctl show -p SubState --value "$SERVICE"))"
    enabled="$(systemctl is-enabled "$SERVICE" 2>/dev/null || true)"
    pid="$(systemctl show -p MainPID --value "$SERVICE")"
    restarts="$(systemctl show -p NRestarts --value "$SERVICE")"
    printf '  %-26s %s\n' "$SERVICE.service" "$state, $enabled at boot, PID $pid, $restarts restarts"
    [ "$INSTALL_CADDY" = yes ] && printf '  %-26s %s\n' "caddy.service" "$(systemctl show -p ActiveState --value caddy) ($(systemctl show -p SubState --value caddy))"
    [ "$PROXY" = builtin ] && printf '  %-26s %s\n' "built-in web server" "$(try jq -r '"revision \(.appliedRevision), ports \([.listeners[]? | .port] | join(" ")), kernel TLS " + (if .kernelTls.on then "on" else "off" end)' "$EDGE_STATUS")"

    section "Setup (saved in $ENV_FILE)"
    printf '  %-30s %s\n' "Version" "$AM_VERSION" "Installation folder" "$APP_ROOT" "Program" "$(readlink -f "$CURRENT")" \
        "Config folder" "$CONFIG" "Logs folder" "$LOGS" "Docker data folder" "$DOCKER_DATA" "IP" "$SERVER_IP" \
        "Server name" "$SERVER_NAME" "API Maker port" "$API_PORT (APIs and web sockets)"
    [ "$KIND" = PRIMARY ] && printf '  %-30s %s\n' "Admin panel port" "$PANEL_PORT"
    if [ "$KIND" = PRIMARY ] && [ "$INSTALL_MONGO" = yes ]; then
        printf '  %-30s %s\n' "MongoDB port" "$MONGO_PORT" "MongoDB user name" "$MONGO_USER" "MongoDB password" "$MONGO_PASSWORD"
    fi
    if [ "$KIND" = PRIMARY ] && [ "$INSTALL_REDIS" = yes ]; then
        printf '  %-30s %s\n' "Redis port" "$REDIS_PORT" "Redis password" "$REDIS_PASSWORD"
    fi
    printf '  %-30s %s\n' "passCommunication" "$PASS_COMMUNICATION" "passJWT" "$PASS_JWT" "passDBEncryptDecrypt" "$PASS_DB"

    section "Important URLs"
    [ -n "$PANEL_URL" ] && printf '  %-30s %s\n' "Admin panel" "$PANEL_URL"
    printf '  %-30s %s\n' "APIs" "$API_URL" "Web sockets" "$WS_URL"

    if [ "$KIND" = PRIMARY ]; then
        section "Default users (change their passwords after the first sign in)"
        printf '  %-30s %s\n' "root@root.com" "R00t_123456789" "admin@admin.com" "Admin_123456789"
        printf '  %-30s %s\n' "Before you go live" "https://docs.apimaker.dev/v4/docs/security/go-live.html"
    fi

    section "Commands"
    printf '  %-12s %s\n' "[START]" "systemctl start $SERVICE" "[STOP]" "systemctl stop $SERVICE" "[RESTART]" "systemctl restart $SERVICE" \
        "[STATUS]" "systemctl status $SERVICE" "[LOGS]" "tail -f $LOG_FILE" "[UPGRADE]" "bash install.sh --version=latest"
    [ "$PROXY" = builtin ] && printf '  %-12s %s\n' "[WEB]" "$CURRENT/api_maker_be edge status --envPath=$ENV_FILE  (settings : $EDGE_FILE)"
    return 0
}

print_secondary_note() {
    [ "$KIND" = SECONDARY ] || return 0
    if [ "$PROXY" = builtin ]; then
        section "Attach this secondary server to the primary server"
        note "API Maker here takes the connections the built-in web server of the primary server ($PRIMARY_IP) shares with it."
        note "On the primary server, add $SERVER_IP:$API_PORT to its other API Maker servers : the Web Server page of its admin panel"
        note "(Other API Maker servers), or apiMaker.gateway.servers in $EDGE_FILE there (applied within two seconds)."
        note "Port $API_PORT of this server has to be reachable from the primary server (and from nowhere else : a firewall rule)."
        return 0
    fi
    section "Attach this secondary server to the primary server"
    note "The APIs of this server answer at $API_URL already. To keep one address for all the servers, list this one in the"
    note "Caddyfile of the primary server ($CADDYFILE there), after the address of API Maker on that server :"
    printf '\n    reverse_proxy 127.0.0.1:%s  →  reverse_proxy 127.0.0.1:%s %s:%s\n\n' "$API_PORT" "$API_PORT" "$SERVER_IP" "$API_PORT"
    note "Then on the primary server : systemctl restart caddy"
    note "Port $API_PORT of this server has to be reachable from the primary server (and from nowhere else : a firewall rule)."
}

main() {
    printf '%s———— API Maker v%s installer ————%s\n' "$C_BOLD" "$AM_MAJOR" "$C_OFF"
    [ "$ARG_DEFAULT" = 1 ] && info "Default installation : every question with a default takes it."
    printf '  Version : %s%s\n' "$ARG_VERSION" "$([ -n "$ARG_PACKAGE" ] && printf ' (from %s)' "$ARG_PACKAGE")"
    [ -n "$ARG_LICENSE_KEY" ] && printf '  License key : given\n'
    local started=$SECONDS

    check_server
    mkdir -p "$LOGS/install"
    INSTALL_LOG="$LOGS/install/install-$(date '+%Y-%m-%d_%H-%M-%S').log"
    : >"$INSTALL_LOG"
    chmod 600 "$INSTALL_LOG"
    install_base_packages
    load_old_env
    detect_earlier_edition

    section "Questions"
    ask_kind
    ask_ip
    ask_proxy
    ask_domains
    ask_environment
    ask_swap
    # The ports API Maker had are free for the questions below.
    stop_api_maker
    leave_pm2
    if [ "$KIND" = PRIMARY ]; then
        ask_mongo
        ask_redis
        # MongoDB and Redis of an earlier installer that stay : they move to the network of the server.
        plan_mongo_move
        plan_redis_move
        # MongoDB with the public key of the installer of v3 : it gets a new key.
        plan_mongo_key
    fi
    ask_api_maker
    print_answers

    section "Installation"
    make_folders
    set_swap
    install_docker
    set_network_limits
    install_mongo
    install_redis
    install_oracle_client
    download_release
    stage_release
    carry_over_old_files
    get_license
    work_out_urls
    write_env
    write_services
    write_edge
    start_api_maker
    [ "$PROXY" = none ] && EDGE_TURNED_OFF=0
    finish_edge
    install_caddy
    reset_license_mac_address
    prune_releases

    print_summary
    print_secondary_note
    printf '\n🍻  Installed in %s seconds. The log of the installer : %s\n' "$((SECONDS - started))" "$INSTALL_LOG"
    printf '\n❤️  Thank you for using API Maker, enjoy !! ❤️\n\n'
}

main
