#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
#
# Install or update Zerodot on a Linux server: Ubuntu, Debian, Fedora, RHEL (Rocky, Alma) or Arch.
# HTTPS comes from Caddy (default), nginx with certbot, or a Cloudflare Tunnel.
# macOS 13+: Docker mode only (Docker Desktop or OrbStack). Run it without sudo.
#
#   sudo bash install.sh zerodot.example.com                      # asks what it needs to ask
#   sudo bash install.sh --check                                  # looks at the server, changes nothing
#   sudo bash install.sh zerodot.example.com --native             # without Docker
#   sudo bash install.sh zerodot.example.com --proxy nginx        # nginx on this server
#   sudo bash install.sh zerodot.example.com --proxy cloudflared  # Cloudflare Tunnel, no open ports
#   sudo bash install.sh zerodot.example.com --postgres host --valkey host   # Docker, host database
#   sudo bash install.sh zerodot.example.com --port 8080 --version 0.2.25    # own port, fixed release
#   sudo bash install.sh zerodot.example.com --admin-email me@example.com --disable-signup
#   sudo bash install.sh zerodot.example.com --backup daily --auto-update weekly
#
# Run it again to update. It keeps your .env and your secrets.
# Run `bash install.sh --help` for all options.
set -euo pipefail

# Windows (Git Bash, MSYS2, Cygwin): hand over to install.ps1. WSL is Linux and stays here.
case "$(uname -s)" in
  MINGW* | MSYS* | CYGWIN*)
    ps1="$(cd "$(dirname "$0")" 2>/dev/null && pwd)/install.ps1"
    [[ -f "$ps1" ]] || { echo "error: on Windows, run scripts/install.ps1 in PowerShell (not found next to this script)." >&2; exit 1; }
    # install.ps1 takes PowerShell options: map the ones that mean the same.
    args=()
    sets=""
    while (($#)); do
      case "$1" in
        --check) args+=(-Check) ;;
        --update) args+=(-Update) ;;
        -y | --yes) args+=(-Yes) ;;
        --name) args+=(-Name "${2:-}"); shift ;;
        --dir) args+=(-Dir "${2:-}"); shift ;;
        --proxy) args+=(-Proxy "${2:-}"); shift ;;
        --no-proxy) args+=(-Proxy none) ;;
        --local) ;;
        --port) args+=(-Port "${2:-}"); shift ;;
        --bind) args+=(-Bind "${2:-}"); shift ;;
        --version) args+=(-Version "${2:-}"); shift ;;
        --image) args+=(-Image "${2:-}"); shift ;;
        --admin-email | --admin-emails) args+=(-AdminEmail "${2:-}"); shift ;;
        --disable-signup) args+=(-DisableSignup) ;;
        --enable-signup) args+=(-EnableSignup) ;;
        --trusted-origins) args+=(-TrustedOrigins "${2:-}"); shift ;;
        # PowerShell takes -Set once: all settings go through one file.
        --set) sets+="${2:-}"$'\n'; shift ;;
        --env-file) [[ -r "${2:-}" ]] || { echo "error: cannot read ${2:-}." >&2; exit 1; }; sets="$(cat "$2")"$'\n'"$sets"; shift ;;
        --uninstall) args+=(-Uninstall) ;;
        --purge) args+=(-Purge) ;;
        -*) echo "error: $1 is not available on Windows. See: install.ps1 (Docker mode, localhost or Cloudflare Tunnel)." >&2; exit 1 ;;
        *) args+=(-Domain "$1") ;;
      esac
      shift
    done
    if [[ -n "$sets" ]]; then
      envf=$(mktemp)
      printf '%s' "$sets" >"$envf"
      command -v cygpath >/dev/null && envf=$(cygpath -w "$envf")
      args+=(-EnvFile "$envf")
    fi
    command -v cygpath >/dev/null && ps1=$(cygpath -w "$ps1")
    exec powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$ps1" "${args[@]}"
    ;;
esac

# macOS has bash 3.2 in /bin. The script needs bash 4.4 or newer: use the Homebrew bash.
if ((BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 4))); then
  for b in /opt/homebrew/bin/bash /usr/local/bin/bash; do
    [[ -x "$b" ]] && exec "$b" "$0" "$@"
  done
  echo "error: bash ${BASH_VERSION} is too old. Install a newer bash (macOS: brew install bash), then run again." >&2
  exit 1
fi

IS_MAC=0
case "$(uname -s)" in
  Linux) ;;
  Darwin) IS_MAC=1 ;;
  *) echo "error: install.sh runs on Linux or macOS only. On Windows, use scripts/install.ps1." >&2; exit 1 ;;
esac

ZERODOT_REPO="${ZERODOT_REPO:-https://github.com/zerodot-io/zerodot.git}"
ZERODOT_BRANCH="${ZERODOT_BRANCH:-}"
CADDYFILE="/etc/caddy/Caddyfile"
((IS_MAC == 0)) || CADDYFILE="$(brew --prefix 2>/dev/null || echo /opt/homebrew)/etc/Caddyfile"
STATE_FILE=".zerodot-install"
# systemd can start a job without HOME.
((IS_MAC)) || export HOME="${HOME:-/root}"

DOMAIN=""
MODE=""            # docker | native
ACTION=""          # update | new
NAME=""
DIR_ARG="${ZERODOT_DIR:-}"
YES=0
CHECK=0
PROXY=""          # caddy | nginx | cloudflared | none
PROXY_ARG=""
PG_MODE=""        # Docker mode: docker | host | url
RD_MODE=""        # Docker mode: docker | host | url
NO_TUI=0
ALLOW_HOST_CHANGES=0
ADDR=""           # domain | sslip | ip
SCHEME=https
DO_SWAP=""        # 1 | 0 | empty = ask
DO_FIREWALL=""
DO_CERTBOT=""
TUNNEL_TOKEN="${ZERODOT_TUNNEL_TOKEN:-}"
PORT_ARG="${ZERODOT_PORT:-}"  # the app port. Docker: the proxy container. Native: the web service.
API_PORT_ARG=""; WORKER_PORT_ARG=""; SANDBOX_PORT_ARG=""
BIND_ARG=""        # the address the app port listens on
VERSION_ARG=""     # latest | X.Y.Z
DATA_DIR_ARG=""
FILES_DIR_ARG=""
BACKUP_ARG=""      # daily | weekly | off
BACKUP_DIR_ARG=""
BACKUP_KEEP_ARG=""
AUTO_UPDATE_ARG="" # daily | weekly | off
UNINSTALL=0
PURGE=""           # with --uninstall: 1 = also remove the data and the folder
SETUP=""           # recommended | advanced. A new install asks.
REINSTALL=0        # 1: remove the install (data too), then set it up again
DONE=1             # 0: the install has not finished yet (a run stopped half-way)
AUTO=0             # 1: the questions take their default answer (recommended setup)
ENV_SETS=()        # KEY=VALUE for .env, from the options. The last one for a key wins.

usage() {
  cat <<'EOF'
Usage: install.sh [domain] [options]

  domain          Public address, for example zerodot.example.com. Without it, the script asks.

  --no-domain     No domain: use <server-ip>.sslip.io, with HTTPS (needs ports 80 and 443).
  --ip            No domain: use the server IP over plain HTTP. For tests or a private network only.
  --local         Only on this computer: http://localhost:PORT, no proxy. Default on macOS.

  --docker        Run with Docker Compose (default).
  --native        Run without Docker: systemd services, host Postgres and Valkey. Linux only.
  --update        Update an install that exists. Skips the question.
  --new           Set up another instance. Skips the question.
  --name NAME     Name of the instance (default: zerodot). Used for the folder, services and database.
  --dir PATH      Folder for the code (default: /var/www/NAME; macOS: ~/NAME).
  --proxy KIND    Who receives the web traffic: caddy (default), nginx, cloudflared or none.
                  macOS: caddy (Homebrew), cloudflared or none.
                  none: the script changes no proxy and prints the upstream.
  --no-proxy      Same as --proxy none.
  --postgres WHERE  docker (own container; Docker mode only) or host (Postgres on this server).
                  For another Postgres, set DATABASE_URL.
  --valkey WHERE    docker (own container; Docker mode only) or host (Valkey/Redis on this server).
                  For another Valkey, set VALKEY_URL.
  --no-tui        Plain questions instead of dialog screens.
  --allow-host-changes
                  With --yes: let the script change Postgres, Valkey, SELinux and nginx.conf
                  settings that other apps can share. Without it, --yes stops before such a change.
  --swap, --no-swap          Add 3 GB swap when RAM is low (default: yes).
  --firewall, --no-firewall  Allow ports 80 and 443 in ufw or firewalld (default: yes).
  --certbot, --no-certbot    nginx: get a certificate from Let's Encrypt (default: yes).
  --check         Look at the server and say what would happen. Changes nothing.
  --recommended   New install: ask only the address. The script picks the rest (default with --yes).
  --advanced      New install: ask about each choice: mode, proxy, database, port, admins and more.
  -y, --yes       Do not ask. Use the default answer.
  -h, --help      This text.

Port and network:
  --port N        Port of the app on this server (default: first free from 3000).
                  Docker: the proxy container. Native: the web service.
  --api-port N, --worker-port N, --sandbox-port N
                  Native mode: the ports of the other services (default: first free).
  --bind ADDR     IPv4 address the app port listens on (default: 127.0.0.1, so only a proxy on
                  this server can reach it). 0.0.0.0: all networks, for a LAN without a proxy.

Version:
  --version V     Install this release, for example 0.2.25. Updates stay on it until you give
                  another one. latest: follow the newest release (default).
  --image REPO    Docker image without the tag (default: ghcr.io/zerodot-io/zerodot). For a mirror.

Users and access:
  --admin-email LIST      Instance admins, comma separated. They can sign up when signup is off.
  --disable-signup        No public signup. Only admin emails and invited people can sign up.
  --enable-signup         Public signup on again (on by default).
  --trusted-origins LIST  More origins that may sign in, comma separated.

Resources and data:
  --concurrency N         Runs at once in each worker (default: 20).
  --workers N             Docker mode: worker containers (default: 1).
  --sandboxes N           Docker mode: code sandbox containers (default: 1).
  --run-retention DAYS    Keep run history this many days (default: 30).
  --stats-retention DAYS  Keep statistics this many days (default: 365).
  --files-dir PATH        Turn on Read/Write Files. Workflows reach only this folder (default: off).
                          Pick a folder outside the install and outside a web root, for example /var/lib/NAME/files.
  --data-dir PATH         Keep files and installed node packages in PATH (default: Docker volumes;
                          native: /var/lib/NAME). New installs only: the script does not move data.

Features:
  --no-update-check       Do not look for new releases.
  --no-feedback-widget    No feedback button in the app.
  --no-admin-ui           No System page.
  --community-nodes       Allow node packages from community registries.
  --npm-registry URL      npm registry for node packages (for a mirror).
  --enable-execute-command
                          Let workflows run shell commands. Dangerous: only when you trust every user.

Any setting:
  --set KEY=VALUE         Write KEY=VALUE to .env. Give it again for more keys. See .env.example.
  --env-file FILE         Write each KEY=VALUE line of FILE to .env.

Maintenance:
  --backup WHEN           Back up the database and .env: daily, weekly or off (default: off).
  --backup-dir PATH       Folder for backups (default: /var/backups/NAME; macOS: ~/NAME-backups).
  --backup-keep N         Keep the newest N backups (default: 14).
  --auto-update WHEN      Update this install by itself: daily, weekly or off (default: off).
  --acme-email EMAIL      Email for Let's Encrypt (--proxy nginx). Same as CERTBOT_EMAIL.
  --uninstall             Stop and remove the services of an install. Keeps the folder, the data
                          and the proxy site, and prints how to remove them.
  --purge                 With --uninstall: also remove the database, the files and the folder.
                          A copy of .env stays in your home folder. Cannot be undone.

Options that you do not give again keep their value on an update.

Environment variables:
  ZERODOT_REPO       Git address of the code.
  ZERODOT_BRANCH     Branch to install (default: the default branch of the repository).
  ZERODOT_DIR        Same as --dir.
  ZERODOT_PORT       Same as --port.
  DATABASE_URL       Use this Postgres and do not create a database (both modes).
  VALKEY_URL         Use this Valkey or Redis and do not install one (both modes).
  ZERODOT_TUNNEL_TOKEN  Token of a Cloudflare Tunnel (--proxy cloudflared). Else the script asks.
  CERTBOT_EMAIL      Email for Let's Encrypt (--proxy nginx). Optional.
EOF
}

opt_fail() { echo "$*" >&2; exit 1; }
# opt_value OPTION VALUE: the option needs a value.
opt_value() { [[ -n "$2" && "$2" != --* ]] || opt_fail "$1 needs a value (see --help)."; }
# opt_number OPTION VALUE MIN
opt_number() { opt_value "$1" "$2"; [[ "$2" =~ ^[0-9]+$ ]] && ((10#$2 >= $3)) || opt_fail "$1 must be a whole number, $3 or more."; }
valid_port() { [[ "$1" =~ ^[0-9]+$ ]] && ((10#$1 >= 1 && 10#$1 <= 65535)); }
opt_port() { opt_value "$1" "$2"; valid_port "$2" || opt_fail "$1 must be a port number (1-65535)."; }
opt_when() { opt_value "$1" "$2"; [[ "$2" =~ ^(daily|weekly|off)$ ]] || opt_fail "$1 must be daily, weekly or off."; }
# Keys that the script manages itself. --set cannot change them.
env_key_ok() {
  [[ "$1" =~ ^[A-Z_][A-Z0-9_]*$ ]] || opt_fail "'$1' is not a setting name (A-Z, 0-9 and _)."
  case "$1" in
    ZERODOT_SECRET_KEY | BETTER_AUTH_SECRET) opt_fail "$1 holds the keys of saved data. Change it by hand (see pnpm rotate-key), not with --set." ;;
    DATABASE_URL | VALKEY_URL) opt_fail "Give $1 as an environment variable: $1=... bash install.sh ..." ;;
    ZERODOT_BASE_URL) opt_fail "ZERODOT_BASE_URL comes from the domain. Give the domain instead." ;;
    ZERODOT_BLOB_DIR | ZERODOT_NODES_DIR) opt_fail "$1 comes from --data-dir." ;;
    ZERODOT_FILES_DIR | ZERODOT_FILES_HOST_DIR) opt_fail "$1 comes from --files-dir." ;;
    ZERODOT_DB_PASSWORD | ZERODOT_VALKEY_PASSWORD | ZERODOT_TUNNEL_TOKEN | SANDBOX_URL) opt_fail "The script sets $1. Change it in .env by hand." ;;
  esac
}
# env_opt KEY=VALUE
env_opt() {
  env_key_ok "${1%%=*}"
  [[ "$1" != *$'\n'* ]] || opt_fail "The value of ${1%%=*} has a line break."
  ENV_SETS+=("$1")
}
# env_file FILE: KEY=VALUE lines. Empty lines, # comments and 'export ' are allowed.
env_file() {
  local line key value
  [[ -r "$1" ]] || opt_fail "Cannot read $1."
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line%$'\r'}"
    [[ "$line" =~ ^[[:space:]]*(#|$) ]] && continue
    line="${line#export }"
    [[ "$line" == *=* ]] || opt_fail "$1: '$line' is not KEY=VALUE."
    key="${line%%=*}"; value="${line#*=}"
    # One pair of quotes around the value goes.
    if [[ "$value" =~ ^\"(.*)\"$ || "$value" =~ ^\'(.*)\'$ ]]; then value="${BASH_REMATCH[1]}"; fi
    env_opt "${key}=${value}"
  done <"$1"
}

while (($#)); do
  case "$1" in
    --docker) MODE=docker ;;
    --native) MODE=native ;;
    --update) ACTION=update ;;
    --new) ACTION=new ;;
    --name) NAME="${2:-}"; shift ;;
    --dir) DIR_ARG="${2:-}"; shift ;;
    --proxy) PROXY_ARG="${2:-}"; shift ;;
    --no-proxy) PROXY_ARG=none ;;
    --postgres) PG_MODE="${2:-}"; shift ;;
    --valkey) RD_MODE="${2:-}"; shift ;;
    --check) CHECK=1 ;;
    --allow-host-changes) ALLOW_HOST_CHANGES=1 ;;
    --no-domain) ADDR=sslip ;;
    --ip) ADDR=ip; SCHEME=http ;;
    --local) ADDR=local; SCHEME=http; PROXY_ARG=none ;;
    --swap) DO_SWAP=1 ;;
    --no-swap) DO_SWAP=0 ;;
    --firewall) DO_FIREWALL=1 ;;
    --no-firewall) DO_FIREWALL=0 ;;
    --certbot) DO_CERTBOT=1 ;;
    --no-certbot) DO_CERTBOT=0 ;;
    --no-tui) NO_TUI=1 ;;
    --port) opt_port "$1" "${2:-}"; PORT_ARG="$2"; shift ;;
    --api-port) opt_port "$1" "${2:-}"; API_PORT_ARG="$2"; shift ;;
    --worker-port) opt_port "$1" "${2:-}"; WORKER_PORT_ARG="$2"; shift ;;
    --sandbox-port) opt_port "$1" "${2:-}"; SANDBOX_PORT_ARG="$2"; shift ;;
    --bind) opt_value "$1" "${2:-}"; BIND_ARG="$2"; shift ;;
    --version) opt_value "$1" "${2:-}"; VERSION_ARG="$2"; shift ;;
    --image) opt_value "$1" "${2:-}"; env_opt "ZERODOT_IMAGE=$2"; shift ;;
    --admin-email | --admin-emails) opt_value "$1" "${2:-}"; env_opt "ZERODOT_ADMIN_EMAILS=$2"; shift ;;
    --disable-signup) env_opt ZERODOT_SIGNUP_DISABLED=true ;;
    --enable-signup) env_opt ZERODOT_SIGNUP_DISABLED=false ;;
    --trusted-origins) opt_value "$1" "${2:-}"; env_opt "ZERODOT_TRUSTED_ORIGINS=$2"; shift ;;
    --concurrency) opt_number "$1" "${2:-}" 1; env_opt "ZERODOT_WORKER_CONCURRENCY=$2"; shift ;;
    --workers) opt_number "$1" "${2:-}" 1; env_opt "WORKER_REPLICAS=$2"; shift ;;
    --sandboxes) opt_number "$1" "${2:-}" 1; env_opt "SANDBOX_REPLICAS=$2"; shift ;;
    --run-retention) opt_number "$1" "${2:-}" 1; env_opt "ZERODOT_RUN_RETENTION_DAYS=$2"; shift ;;
    --stats-retention) opt_number "$1" "${2:-}" 1; env_opt "ZERODOT_STATS_RETENTION_DAYS=$2"; shift ;;
    --data-dir) opt_value "$1" "${2:-}"; DATA_DIR_ARG="${2%/}"; shift ;;
    --files-dir) opt_value "$1" "${2:-}"; FILES_DIR_ARG="${2%/}"; shift ;;
    --no-update-check) env_opt ZERODOT_UPDATE_CHECK=false ;;
    --no-feedback-widget) env_opt ZERODOT_FEEDBACK_WIDGET=false ;;
    --no-admin-ui) env_opt ZERODOT_ADMIN_UI=false ;;
    --community-nodes) env_opt ZERODOT_COMMUNITY_NODES=true ;;
    --npm-registry) opt_value "$1" "${2:-}"; env_opt "ZERODOT_NPM_REGISTRY=$2"; shift ;;
    --enable-execute-command) env_opt ZERODOT_ENABLE_EXECUTE_COMMAND=true ;;
    --set) opt_value "$1" "${2:-}"; [[ "$2" == *=* ]] || opt_fail "--set needs KEY=VALUE."; env_opt "$2"; shift ;;
    --env-file) opt_value "$1" "${2:-}"; env_file "$2"; shift ;;
    --backup) opt_when "$1" "${2:-}"; BACKUP_ARG="$2"; shift ;;
    --backup-dir) opt_value "$1" "${2:-}"; BACKUP_DIR_ARG="${2%/}"; shift ;;
    --backup-keep) opt_number "$1" "${2:-}" 1; BACKUP_KEEP_ARG="$2"; shift ;;
    --auto-update) opt_when "$1" "${2:-}"; AUTO_UPDATE_ARG="$2"; shift ;;
    --acme-email) opt_value "$1" "${2:-}"; CERTBOT_EMAIL="$2"; shift ;;
    --uninstall) UNINSTALL=1 ;;
    --purge) PURGE=1 ;;
    --recommended) SETUP=recommended ;;
    --advanced) SETUP=advanced ;;
    -y | --yes) YES=1 ;;
    -h | --help) usage; exit 0 ;;
    -*) echo "Unknown option: $1 (see --help)" >&2; exit 1 ;;
    *) DOMAIN="$1" ;;
  esac
  shift
done
[[ -z "$PROXY_ARG" || "$PROXY_ARG" =~ ^(caddy|nginx|cloudflared|none)$ ]] || { echo "--proxy must be caddy, nginx, cloudflared or none." >&2; exit 1; }
[[ -z "$PG_MODE" || "$PG_MODE" =~ ^(docker|host)$ ]] || { echo "--postgres must be docker or host." >&2; exit 1; }
[[ -z "$RD_MODE" || "$RD_MODE" =~ ^(docker|host)$ ]] || { echo "--valkey must be docker or host." >&2; exit 1; }
[[ -z "$PORT_ARG" ]] || valid_port "$PORT_ARG" || opt_fail "ZERODOT_PORT must be a port number (1-65535)."
[[ -z "$BIND_ARG" || "$BIND_ARG" =~ ^[0-9]+(\.[0-9]+){3}$ ]] || opt_fail "--bind must be an IPv4 address, for example 127.0.0.1 or 0.0.0.0."
if [[ -n "$VERSION_ARG" ]]; then
  VERSION_ARG="${VERSION_ARG#v}"
  [[ "$VERSION_ARG" == latest || "$VERSION_ARG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] \
    || opt_fail "--version must be latest or a release such as 0.2.25."
  [[ -z "$ZERODOT_BRANCH" ]] || opt_fail "Give --version or ZERODOT_BRANCH, not both."
fi
[[ -z "$FILES_DIR_ARG" || "$FILES_DIR_ARG" == /* ]] || opt_fail "--files-dir must be a full path (starts with /)."
case "$FILES_DIR_ARG" in
  / | /etc* | /usr* | /bin* | /sbin* | /boot* | /proc* | /sys* | /dev* | /root* | /var/www*)
    opt_fail "--files-dir $FILES_DIR_ARG is not a safe folder for files. Use a folder such as /var/lib/NAME/files." ;;
esac
[[ -z "$DATA_DIR_ARG" || "$DATA_DIR_ARG" == /* ]] || opt_fail "--data-dir must be a full path (starts with /)."
[[ -z "$BACKUP_DIR_ARG" || "$BACKUP_DIR_ARG" == /* ]] || opt_fail "--backup-dir must be a full path (starts with /)."
((UNINSTALL == 0 || CHECK == 0)) || opt_fail "Give --uninstall or --check, not both."
[[ -z "$PURGE" ]] || ((UNINSTALL)) || opt_fail "--purge goes with --uninstall."

# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------
if [[ -t 1 ]]; then B=$'\033[1m'; G=$'\033[32m'; Y=$'\033[33m'; R=$'\033[31m'; N=$'\033[0m'; else B=""; G=""; Y=""; R=""; N=""; fi
FAILS=0
WARNS=0
SUGGEST=()

banner() {
  printf '%s' "$B"
  cat <<'ART'

     _____                         _         _
    |__  /  ___   _ __   ___    __| |  ___  | |_
      / /  / _ \ | '__| / _ \  / _` | / _ \ | __|
     / /_ |  __/ | |   | (_) || (_| || (_) || |_
    /____| \___| |_|    \___/  \__,_| \___/  \__|
ART
  printf '%s   Start with a dot.  ·  installer\n\n' "$N"
}

say() { printf '\n%s==> %s%s\n' "$B" "$*" "$N"; }
ok() { printf '  %s✔%s %s\n' "$G" "$N" "$*"; }
note() { printf '  %s!%s %s\n' "$Y" "$N" "$*"; WARNS=$((WARNS + 1)); }
bad() { printf '  %s✘%s %s\n' "$R" "$N" "$*"; FAILS=$((FAILS + 1)); }
tip() { SUGGEST+=("$*"); }
die() { printf '%serror:%s %s\n' "$R" "$N" "$*" >&2; exit 1; }

have_tty() { [[ -e /dev/tty ]] && (: </dev/tty) 2>/dev/null; }

# ask "prompt" "default"  -> REPLY. Uses the default when --yes or no terminal.
ask() {
  local prompt="$1" default="${2:-}"
  if ((YES)) || ! have_tty; then REPLY="$default"; return; fi
  read -r -p "$prompt" REPLY </dev/tty || REPLY="$default"
  REPLY="${REPLY:-$default}"
}
confirm() { ask "$1 [Y/n] " "Y"; [[ "$REPLY" =~ ^[Yy] ]]; }

# Dialog screens (whiptail). Used on a real terminal unless --no-tui or --yes.
TUI=0
init_tui() {
  if ((NO_TUI == 0 && YES == 0)) && have_tty && [[ -t 1 ]] && [[ "${TERM:-dumb}" != dumb ]] && command -v whiptail >/dev/null 2>&1; then
    TUI=1
  fi
  return 0
}
tui_cancel() { echo; echo "Stopped. Nothing was changed."; exit 0; }
# tui_menu TITLE TEXT TAG ITEM [TAG ITEM ...]  -> REPLY
tui_menu() {
  local title="$1" text="$2"
  shift 2
  REPLY=$(whiptail --title "$title" --menu "$text" 22 78 "$(($# / 2))" "$@" 3>&1 1>&2 2>&3 </dev/tty) || tui_cancel
}
# tui_input TITLE TEXT DEFAULT  -> REPLY
tui_input() { REPLY=$(whiptail --title "$1" --inputbox "$2" 11 78 "$3" 3>&1 1>&2 2>&3 </dev/tty) || tui_cancel; }
# tui_yesno TITLE TEXT  -> status
tui_yesno() { whiptail --title "$1" --yesno "$2" 22 78 </dev/tty; }
# ask_secret PROMPT  -> REPLY. Does not show what is typed.
ask_secret() {
  REPLY=""
  if ((YES)) || ! have_tty; then return; fi
  if ((TUI)); then
    REPLY=$(whiptail --title "Secret" --passwordbox "$1" 11 78 3>&1 1>&2 2>&3 </dev/tty) || tui_cancel
  else
    read -r -s -p "$1 " REPLY </dev/tty || REPLY=""
    echo
  fi
}
# choose TITLE TEXT DEFAULT TAG LABEL [TAG LABEL ...]  -> REPLY (a TAG).
# A menu on a terminal. With --yes or no terminal: DEFAULT.
choose() {
  local title="$1" text="$2" def="$3" i n
  shift 3
  REPLY="$def"
  if ((YES || AUTO)) || ! have_tty; then return 0; fi
  local args=("$@")
  n=$((${#args[@]} / 2))
  if ((TUI)); then
    REPLY=$(whiptail --title "$title" --default-item "$def" --menu "$text" 22 78 "$n" "${args[@]}" 3>&1 1>&2 2>&3 </dev/tty) || tui_cancel
    return 0
  fi
  printf '\n%s%s%s\n%s\n' "$B" "$title" "$N" "$text"
  local d=1
  for ((i = 0; i < n; i++)); do
    [[ "${args[2 * i]}" == "$def" ]] && d=$((i + 1))
    printf '  %d) %s\n' $((i + 1)) "${args[2 * i + 1]}"
  done
  ask "Choose [1-$n, default $d]: " "$d"
  [[ "$REPLY" =~ ^[0-9]+$ ]] && ((REPLY >= 1 && REPLY <= n)) || die "Not a valid choice."
  REPLY="${args[2 * (REPLY - 1)]}"
}

# choose_many TITLE TEXT TAG LABEL on|off [...]  -> CHOSEN (the TAGs that are on).
# A checklist on a terminal. With --yes or no terminal: the ones marked on.
CHOSEN=()
choose_many() {
  local title="$1" text="$2" i n out
  shift 2
  local args=("$@")
  n=$((${#args[@]} / 3))
  CHOSEN=()
  ((n > 0)) || return 0
  if ((YES || AUTO)) || ! have_tty; then
    for ((i = 0; i < n; i++)); do [[ "${args[3 * i + 2]}" == on ]] && CHOSEN+=("${args[3 * i]}"); done
    return 0
  fi
  if ((TUI)); then
    local items=()
    for ((i = 0; i < n; i++)); do items+=("${args[3 * i]}" "${args[3 * i + 1]}" "$([[ ${args[3 * i + 2]} == on ]] && echo ON || echo OFF)"); done
    out=$(whiptail --title "$title" --separate-output --checklist "$text\n(Space to select, Enter to accept)" 22 78 "$n" "${items[@]}" 3>&1 1>&2 2>&3 </dev/tty) || tui_cancel
    while IFS= read -r i; do [[ -n "$i" ]] && CHOSEN+=("$i"); done <<<"$out"
    return 0
  fi
  printf '\n%s%s%s\n%s\n' "$B" "$title" "$N" "$text"
  for ((i = 0; i < n; i++)); do
    local def=N
    [[ "${args[3 * i + 2]}" == on ]] && def=Y
    ask "  ${args[3 * i + 1]}? [$([[ $def == Y ]] && echo Y/n || echo y/N)] " "$def"
    [[ "$REPLY" =~ ^[Yy] ]] && CHOSEN+=("${args[3 * i]}")
  done
  return 0
}
chosen() { [[ " ${CHOSEN[*]} " == *" $1 "* ]]; }

# input TITLE TEXT DEFAULT  -> REPLY. A text box on a terminal. With --yes or no terminal: DEFAULT.
input() {
  if ((TUI)) && ((YES == 0)) && have_tty; then tui_input "$1" "$2" "$3"; return; fi
  ((YES)) || ! have_tty || printf '\n%s%s%s\n%b\n' "$B" "$1" "$N" "$2"
  ask "$1 [${3:-empty}]: " "$3"
}
# env_value KEY: the value an option gives to KEY (the last one), else empty.
env_value() {
  local kv v=""
  for kv in "${ENV_SETS[@]}"; do [[ "${kv%%=*}" == "$1" ]] && v="${kv#*=}"; done
  printf '%s' "$v"
}

# The public IPv4 address of this server.
public_ip() { curl -s4 --max-time 6 https://api.ipify.org 2>/dev/null || curl -s4 --max-time 6 https://ifconfig.me 2>/dev/null || true; }

# yes_no TITLE TEXT  -> status. Yes with --yes or no terminal.
yes_no() {
  if ((YES)) || ! have_tty; then return 0; fi
  if ((TUI)); then tui_yesno "$1" "$2"; else printf '\n%s\n' "$2"; confirm "$1?"; fi
}
# ask_change TITLE TEXT  -> status. For a change to a service that other apps can use.
# Without a person to ask, only --allow-host-changes says yes.
ask_change() {
  if ((YES)) || ! have_tty; then
    ((ALLOW_HOST_CHANGES)) && return 0
    printf '\n%s\n' "$2" >&2
    return 1
  fi
  if ((TUI)); then tui_yesno "$1" "$2"; else printf '\n%s\n' "$2"; ask "$1? [y/N] " "N"; [[ "$REPLY" =~ ^[Yy] ]]; fi
}

# A Cloudflare Tunnel token -> TUNNEL_TOKEN.
ask_tunnel_token() {
  if [[ -z "$TUNNEL_TOKEN" ]]; then
    printf '\n  Make a tunnel: Cloudflare dashboard > Zero Trust > Networks > Tunnels > Create a tunnel (cloudflared).\n  Copy the token from the install command (the long text after --token).\n'
    ask_secret "Tunnel token:"
    TUNNEL_TOKEN="$REPLY"
  fi
  [[ -n "$TUNNEL_TOKEN" ]] || die "A Cloudflare Tunnel token is needed. Set ZERODOT_TUNNEL_TOKEN and run again."
  # The token is base64 JSON with the account (a), the tunnel (t) and a secret (s).
  [[ "$(printf '%s' "$TUNNEL_TOKEN" | base64 -d 2>/dev/null || true)" == *'"t":'* ]] \
    || die "That is not a tunnel token. Copy the text after --token in the install command of the tunnel."
}

# Parts of a URL such as postgres://user:pass@host:5432/db. IPv6 hosts are not supported.
url_host() { printf '%s' "$1" | sed -E 's#^[a-z]+://([^@/]*@)?([^:/?]+).*#\2#'; }
url_port() { printf '%s' "$1" | sed -nE 's#^[a-z]+://([^@/]*@)?[^:/?]+:([0-9]+).*#\2#p'; }
url_user() { printf '%s' "$1" | sed -nE 's#^[a-z]+://([^:@/]+)(:[^@/]*)?@.*#\1#p'; }
url_pass() { printf '%s' "$1" | sed -nE 's#^[a-z]+://[^:@/]*:([^@/]*)@.*#\1#p'; }
url_path() { printf '%s' "$1" | sed -nE 's#^[a-z]+://[^/]+/([^?]*).*#\1#p'; }
is_local_host() { [[ "$1" == localhost || "$1" == 127.0.0.1 || "$1" == host.docker.internal ]]; }
# Containers reach the host as host.docker.internal.
to_docker_host() { printf '%s' "$1" | sed -E 's#^([a-z]+://([^@/]*@)?)(localhost|127\.0\.0\.1)([:/?]|$)#\1host.docker.internal\4#'; }

ver_ge() { [[ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" == "$2" ]]; }
# Do not write `cmd | grep -q`: grep exits early, cmd gets SIGPIPE, and pipefail reports a failure.
port_in_use() {
  # macOS: netstat shows the listeners of all users. The address ends in .PORT (*.443, 127.0.0.1.3000).
  if ((IS_MAC)); then
    [[ -n "$(netstat -an -p tcp 2>/dev/null | awk -v p=".$1" '$NF == "LISTEN" && substr($4, length($4) - length(p) + 1) == p' || true)" ]]
    return
  fi
  if command -v ss >/dev/null; then [[ -n "$(ss -ltnH "sport = :$1" 2>/dev/null || true)" ]]; return; fi
  # No ss: read the kernel table. State 0A = LISTEN. The port is hex.
  local hex
  hex=$(printf '%04X' "$1")
  [[ -n "$(awk -v p=":$hex" '$4 == "0A" && substr($2, length($2) - 4) == p' /proc/net/tcp /proc/net/tcp6 2>/dev/null)" ]]
}
unit_exists() { local out; out=$(systemctl list-unit-files "$1" 2>/dev/null || true); [[ "$out" == *"$1"* ]]; }
ufw_active() { command -v ufw >/dev/null && [[ "$(ufw status 2>/dev/null || true)" == *"Status: active"* ]]; }
listener() {
  # macOS: lsof sees only the processes of this user. Unknown is the result for the others.
  if ((IS_MAC)); then lsof -nP -iTCP:"$1" -sTCP:LISTEN 2>/dev/null | awk 'NR == 2 {print $1}' || true; return; fi
  ss -ltnpH "sport = :$1" 2>/dev/null | grep -o 'users:(("[^"]*"' | head -1 | cut -d'"' -f2 || true; }

RESERVED=""
FREE_PORT=""
# free_port START  -> sets FREE_PORT. Not run in $(...), so RESERVED keeps the ports it picked.
free_port() {
  local p="$1"
  while port_in_use "$p" || [[ " $RESERVED " == *" $p "* ]]; do p=$((p + 1)); done
  RESERVED="$RESERVED $p"
  FREE_PORT="$p"
}

# ---------------------------------------------------------------------------
# What the script changed. If it stops, it prints the list, so you know the state.
# ---------------------------------------------------------------------------
CHANGES=()
LOCK_DIR=""   # macOS: a lock folder (no flock there)
LOG_FILE=/var/log/zerodot-install.log
((IS_MAC == 0)) || LOG_FILE="$HOME/Library/Logs/zerodot-install.log"
changed() {
  CHANGES+=("$*")
  { printf '%s %s\n' "$(date '+%F %T')" "$*" >> "$LOG_FILE"; } 2>/dev/null || true
}
on_exit() {
  local status=$?
  [[ -z "$LOCK_DIR" ]] || rmdir "$LOCK_DIR" 2>/dev/null || true
  if ((status != 0 && ${#CHANGES[@]} > 0)); then
    printf '\n%sThe script stopped. Before it stopped, it changed:%s\n' "$Y" "$N" >&2
    printf '  - %s\n' "${CHANGES[@]}" >&2
    printf 'Run it again to continue: it skips the steps that are done. Log: %s\n' "$LOG_FILE" >&2
  fi
}

# backup FILE: copy with the time in the name, so an older copy is never overwritten. -> BACKUP
BACKUP=""
backup() {
  BACKUP=""
  [[ -f "$1" ]] || return 0
  local base n=1
  base="$1.bak-zerodot-$(date +%Y%m%d%H%M%S)"
  BACKUP="$base"
  while [[ -e "$BACKUP" ]]; do BACKUP="$base-$n"; n=$((n + 1)); done
  cp -p "$1" "$BACKUP"
  changed "Copy of $1 in $BACKUP"
}

# macOS: Homebrew services (launchd) take the place of systemd.
brew_svc_status() { brew services list 2>/dev/null | awk -v s="$1" '$1 == s {print $2}' || true; }
svc_active() {
  if ((IS_MAC)); then [[ "$(brew_svc_status "$1")" == started ]]; return; fi
  systemctl is-active --quiet "$1" 2>/dev/null
}
# svc_start UNIT: start and enable a service that the script installed.
svc_start() {
  if ((IS_MAC)); then
    if svc_active "$1"; then brew services restart "$1" >/dev/null; else brew services start "$1" >/dev/null; fi
    return
  fi
  systemctl enable "$1" >/dev/null 2>&1 || true
  if svc_active "$1"; then systemctl reload "$1" 2>/dev/null || systemctl restart "$1"; else systemctl start "$1"; fi
}

# ---------------------------------------------------------------------------
# Packages: apt (Debian, Ubuntu), dnf (Fedora, RHEL, Rocky, Alma), pacman (Arch).
# Installed packages are not upgraded, and the system is never upgraded.
# ---------------------------------------------------------------------------
PKG=""          # apt | dnf | pacman
OS_FAMILY=""    # debian | fedora | rhel | arch
PKG_FRESH=0
export DEBIAN_FRONTEND=noninteractive
# needrestart (Ubuntu) must not restart other services after an install. It only lists them.
export NEEDRESTART_MODE=l NEEDRESTART_SUSPEND=1

pkg_refresh() {
  ((PKG_FRESH)) && return 0
  PKG_FRESH=1
  case "$PKG" in
    apt) apt-get -o DPkg::Lock::Timeout=300 update -qq || note "apt-get update failed (a broken repository?). Using the package lists that are on the server." ;;
    dnf) dnf -q makecache >/dev/null 2>&1 || note "dnf makecache failed. Using the cached package lists." ;;
    pacman) ;; # 'pacman -Sy' without '-u' breaks Arch (partial upgrade). Use the local lists.
  esac
}

pacman_wait() {
  local i
  for i in $(seq 1 100); do [[ -e /var/lib/pacman/db.lck ]] || return 0; sleep 3; done
  die "pacman is locked (/var/lib/pacman/db.lck). Wait for the other pacman to finish."
}

# pkg_install PACKAGE...: real package names. Installed packages stay as they are.
pkg_install() {
  pkg_refresh
  local missing=() p
  for p in "$@"; do pkg_installed "$p" || missing+=("$p"); done
  ((${#missing[@]})) || return 0
  local log rc=0
  log=$(mktemp)
  case "$PKG" in
    apt) apt-get -o DPkg::Lock::Timeout=300 install -y -qq --no-upgrade "${missing[@]}" >"$log" 2>&1 || rc=$? ;;
    # No --allowerasing: dnf must not remove other packages (podman, runc...) to make room.
    dnf) dnf install -y -q "${missing[@]}" >"$log" 2>&1 || rc=$? ;;
    pacman)
      pacman_wait
      pacman -S --needed --noconfirm "${missing[@]}" >"$log" 2>&1 || rc=$?
      ((rc == 0)) || { tail -5 "$log" >&2; rm -f "$log"; die "pacman cannot install ${missing[*]} (see above). If it says 'not found' or 404, the package lists are old: run 'pacman -Syu' (full upgrade) yourself, then run this script again."; }
      ;;
  esac
  if ((rc != 0)); then
    note "Could not install: ${missing[*]}"
    tail -8 "$log" >&2
    rm -f "$log"
    return 1
  fi
  rm -f "$log"
  changed "Installed packages: ${missing[*]}"
}
pkg_installed() {
  case "$PKG" in
    apt) [[ "$(dpkg-query -W -f '${Status}' "$1" 2>/dev/null || true)" == "install ok installed" ]] ;;
    dnf) rpm -q --whatprovides "$1" >/dev/null 2>&1 ;;
    pacman) pacman -Qq "$1" >/dev/null 2>&1 ;;
  esac
}
pkg_available() {
  pkg_refresh
  case "$PKG" in
    apt) [[ -n "$(apt-cache policy "$1" 2>/dev/null | awk '/Candidate:/ && $2 != "(none)" {print $2}')" ]] ;;
    dnf) dnf -q info "$1" >/dev/null 2>&1 ;;
    pacman) pacman -Si "$1" >/dev/null 2>&1 ;;
  esac
}
# pkg_first CANDIDATE...: install the first package that exists. -> REPLY (empty if none)
pkg_first() {
  local p
  REPLY=""
  for p in "$@"; do
    if pkg_installed "$p" || pkg_available "$p"; then pkg_install "$p" && { REPLY="$p"; return 0; }; fi
  done
  return 0
}

# Names of the same thing in each family.
pkgs_base() { case "$PKG" in apt) echo git curl openssl ca-certificates iproute2 tar ;; dnf) echo git curl openssl ca-certificates iproute tar ;; pacman) echo git curl openssl ca-certificates iproute2 tar ;; esac; }
pkgs_build() { case "$PKG" in apt) echo python3 make g++ ;; dnf) echo python3 make gcc-c++ ;; pacman) echo python make gcc ;; esac; }
pkgs_pg_client() { case "$PKG" in apt) echo postgresql-client ;; *) echo postgresql ;; esac; }
pkgs_xz() { case "$PKG" in apt) echo xz-utils ;; *) echo xz ;; esac; }
pkgs_certbot() { case "$PKG" in apt | dnf) echo certbot python3-certbot-nginx ;; pacman) echo certbot certbot-nginx ;; esac; }
nologin_shell() { command -v nologin 2>/dev/null || echo /usr/sbin/nologin; }

# Add a package repository file. Repositories that exist are not changed.
add_repo_file() {
  local url="$1" dest="$2"
  [[ -f "$dest" ]] && return 0
  curl -fsSL "$url" -o "$dest" || die "Cannot download $url."
  changed "Added package repository $dest"
  PKG_FRESH=0
}

# ---------------------------------------------------------------------------
# Firewall: ufw or firewalld. The script only adds rules. It never turns a firewall on or off.
# ---------------------------------------------------------------------------
firewalld_active() { command -v firewall-cmd >/dev/null && [[ "$(firewall-cmd --state 2>/dev/null || true)" == running ]]; }
# firewalld: write the rule to the saved config and to the running config. No --reload: on some
# Docker versions a reload removes the rules of Docker.
fwd() { firewall-cmd -q --permanent "$@" && firewall-cmd -q "$@"; }
fw_name() { if ufw_active; then echo ufw; elif firewalld_active; then echo firewalld; fi; }
fw_open_web() {
  if ufw_active; then
    ufw allow 80/tcp >/dev/null && ufw allow 443/tcp >/dev/null && changed "ufw: allowed 80/tcp and 443/tcp"
  elif firewalld_active; then
    fwd --add-service=http && fwd --add-service=https && changed "firewalld: allowed http and https"
  fi
  return 0
}
# fw_allow_from SUBNET ADDRESS PORT: let a Docker network reach a port on the host.
fw_allow_from() {
  if ufw_active; then
    ufw allow from "$1" to "$2" port "$3" proto tcp >/dev/null && changed "ufw: allowed $1 to $2 port $3"
  elif firewalld_active; then
    local zone=docker
    firewall-cmd -q --permanent --info-zone=docker >/dev/null 2>&1 || zone=$(firewall-cmd --get-default-zone)
    fwd --zone="$zone" --add-rich-rule="rule family=ipv4 source address=$1 destination address=$2 port port=$3 protocol=tcp accept" \
      && changed "firewalld ($zone): allowed $1 to $2 port $3"
  fi
  return 0
}

# ---------------------------------------------------------------------------
# SELinux (Fedora, RHEL): nginx and Caddy need a switch to connect to the app.
# ---------------------------------------------------------------------------
selinux_enforcing() { command -v getenforce >/dev/null && [[ "$(getenforce 2>/dev/null)" == Enforcing ]]; }
selinux_allow_proxy() {
  selinux_enforcing || return 0
  # Caddy is confined only on some systems. Look at the SELinux type of its process.
  if [[ "$PROXY" == caddy ]] && svc_active caddy \
    && [[ "$(ps -eo label=,comm= 2>/dev/null | awk '$2 == "caddy" {print $1; exit}')" != *httpd_t* ]]; then
    return 0
  fi
  [[ "$(getsebool httpd_can_network_connect 2>/dev/null || true)" == *" on" ]] && return 0
  ask_change "SELinux" "SELinux stops web servers from opening connections. ${PROXY} must connect to the app on 127.0.0.1.
The script sets the SELinux boolean httpd_can_network_connect to on." \
    || die "SELinux not changed. Run 'setsebool -P httpd_can_network_connect 1', then run again."
  setsebool -P httpd_can_network_connect 1
  changed "SELinux: httpd_can_network_connect on"
}

# ---------------------------------------------------------------------------
# Existing installs
# ---------------------------------------------------------------------------
is_zerodot_dir() { [[ -f "$1/docker-compose.yml" && -f "$1/apps/web/package.json" ]] && grep -q '"@zerodot/web"' "$1/apps/web/package.json"; }
# An install, not only a copy of the code (a developer clone has no .env and no state file).
is_zerodot_install() { is_zerodot_dir "$1" && [[ -f "$1/$STATE_FILE" || -f "$1/.env" ]]; }

# Docker Compose names a project after its folder. Two folders with the same name (a dev
# checkout ~/Developer/zerodot and an install ~/zerodot) share containers and volumes.
compose_project() { basename "$1" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9_-'; }
# project_owner DIR -> the folder of another compose project with the same name, else empty.
project_owner() {
  command -v docker >/dev/null 2>&1 || return 0
  local p real w
  p=$(compose_project "$1")
  real=$(readlink -f "$1" 2>/dev/null || echo "$1")
  while IFS= read -r w; do
    [[ -n "$w" && "$w" != "$1" && "$(readlink -f "$w" 2>/dev/null || echo "$w")" != "$real" ]] && { echo "$w"; return 0; }
  done < <(docker ps -a --filter "label=com.docker.compose.project=$p" --format '{{.Label "com.docker.compose.project.working_dir"}}' 2>/dev/null | sort -u)
  return 0
}
# name_taken NAME: a new install with this name would share Docker containers or data.
name_taken() {
  local dir
  if ((IS_MAC)); then dir="${DIR_ARG:-$HOME/$1}"; else dir="${DIR_ARG:-/var/www/$1}"; fi
  [[ -e "$dir" && -n "$(ls -A "$dir" 2>/dev/null)" ]] && return 0
  command -v docker >/dev/null 2>&1 || return 1
  [[ -n "$(project_owner "$dir")" ]] && return 0
  [[ -n "$(docker volume ls -q --filter "name=^$(compose_project "$dir")_postgres-data\$" 2>/dev/null)" ]]
}

# The app port in docker-compose.override.yml ("127.0.0.1:3000:3000" or "0.0.0.0:3000:3000").
override_port() {
  [[ -f "$1" ]] || return 0
  grep -Eo '"([0-9.]+:)?[0-9]+:3000"' "$1" | head -1 | tr -d '"' | awk -F: '{print $(NF-1)}' || true
}

# state_get DIR KEY. Reads .zerodot-install, else guesses from .env.
state_get() {
  local dir="$1" key="$2" value=""
  if [[ -f "$dir/$STATE_FILE" ]]; then
    value=$(grep -m1 "^${key}=" "$dir/$STATE_FILE" | cut -d= -f2- || true)
  fi
  if [[ -z "$value" ]]; then
    case "$key" in
      DOMAIN) value=$(grep -m1 '^ZERODOT_BASE_URL=' "$dir/.env" 2>/dev/null | cut -d= -f2- | sed -E 's|^https?://||; s|/.*$||' || true) ;;
      NAME) value=$(basename "$dir") ;;
      SCHEME) value=$(grep -m1 '^ZERODOT_BASE_URL=' "$dir/.env" 2>/dev/null | sed -nE 's#^ZERODOT_BASE_URL=(https?)://.*#\1#p' || true); value="${value:-https}" ;;
      MODE)
        if unit_exists "$(basename "$dir")-api.service"; then value=native; else value=docker; fi
        ;;
    esac
  fi
  echo "$value"
}

INSTALLS=()
scan_installs() {
  local d real seen=" "
  local candidates=(/var/www/* /opt/* /srv/* "$HOME"/*)
  if command -v docker >/dev/null 2>&1; then
    while IFS= read -r f; do [[ -n "$f" ]] && candidates+=("$(dirname "$f")"); done < <(
      docker compose ls -a --format json 2>/dev/null | grep -o '"ConfigFiles":"[^",]*' | cut -d'"' -f4 || true
    )
  fi
  for d in "${candidates[@]}"; do
    [[ -d "$d" ]] || continue
    real=$(readlink -f "$d")
    [[ "$seen" == *" $real "* ]] && continue
    seen="$seen$real "
    if is_zerodot_install "$real"; then
      INSTALLS+=("$real")
      for k in WEB_PORT API_PORT WORKER_PORT SANDBOX_PORT PORT; do
        p=$(state_get "$real" "$k")
        [[ "$p" =~ ^[0-9]+$ ]] && RESERVED="$RESERVED $p"
      done
      p=$(override_port "$real/docker-compose.override.yml")
      [[ -n "$p" ]] && RESERVED="$RESERVED $p"
    fi
  done
  return 0
}

install_status() {
  local dir="$1" mode name
  mode=$(state_get "$dir" MODE)
  name=$(state_get "$dir" NAME)
  if [[ "$mode" == native ]]; then
    systemctl is-active --quiet "${name}-api" 2>/dev/null && echo running || echo stopped
  else
    if command -v docker >/dev/null 2>&1 && [[ -n "$(cd "$dir" && docker compose ps -q 2>/dev/null)" ]]; then echo running; else echo stopped; fi
  fi
}

# ---------------------------------------------------------------------------
# Preflight: look at the server. Changes nothing.
# ---------------------------------------------------------------------------
OS_ID=""; OS_VER=""; MEM_MB=0; SWAP_MB=0; ARCH=""; VIRT="none"
HAS_DOCKER=0; DOCKER_OK=0
PG_STATE=none; PG_VERNUM=0; PG_PORT=5432
RD_STATE=none; RD_CLI=""; RD_VERSION=""; RD_POLICY=""; RD_AUTH=0

check_os_mac() {
  OS_ID=macos
  OS_VER=$(sw_vers -productVersion 2>/dev/null || echo 0)
  if ver_ge "$OS_VER" 13; then ok "macOS $OS_VER"; else bad "macOS $OS_VER is too old. Use 13 or newer."; fi
  ARCH=$(uname -m)
  case "$ARCH" in
    x86_64 | arm64) ok "CPU type $ARCH" ;;
    *) bad "CPU type $ARCH is not supported." ;;
  esac
  command -v git >/dev/null || bad "No git. Install the command line tools: xcode-select --install"
  if command -v brew >/dev/null; then ok "Homebrew $(brew --version 2>/dev/null | awk 'NR == 1 {print $2}')"
  else note "No Homebrew. --proxy caddy needs it (https://brew.sh). --proxy none and cloudflared do not."; fi
  ok "Docker mode only on macOS (no systemd)"
}

check_os() {
  ((IS_MAC == 0)) || { check_os_mac; return 0; }
  local id like
  # Read it in a subshell: the file sets NAME, which is also the name of the instance.
  if [[ -r /etc/os-release ]]; then
    OS_ID=$(. /etc/os-release && echo "${ID:-}")
    OS_VER=$(. /etc/os-release && echo "${VERSION_ID:-0}")
    like=$(. /etc/os-release && echo "${ID_LIKE:-}")
  fi
  id="$OS_ID"
  if command -v apt-get >/dev/null; then PKG=apt
  elif command -v dnf >/dev/null; then PKG=dnf
  elif command -v pacman >/dev/null; then PKG=pacman
  fi
  case " $id $like " in
    *" ubuntu "* | *" debian "*) OS_FAMILY=debian ;;
    *" fedora "*) [[ "$id" == fedora ]] && OS_FAMILY=fedora || OS_FAMILY=rhel ;;
    *" rhel "* | *" centos "*) OS_FAMILY=rhel ;;
    *" arch "*) OS_FAMILY=arch ;;
  esac
  case "$id" in
    ubuntu) if ver_ge "$OS_VER" 22.04; then ok "Ubuntu $OS_VER"; else bad "Ubuntu $OS_VER is too old. Use 22.04 or newer."; fi ;;
    debian) if ver_ge "$OS_VER" 12; then ok "Debian $OS_VER"; else bad "Debian $OS_VER is too old. Use 12 or newer."; fi ;;
    fedora) if ver_ge "$OS_VER" 40; then ok "Fedora $OS_VER"; else bad "Fedora $OS_VER is too old. Use 40 or newer."; fi ;;
    rhel | rocky | almalinux | centos | ol)
      if ver_ge "${OS_VER%%.*}" 9; then ok "$id $OS_VER"; else bad "$id $OS_VER is too old. Use version 9 or newer."; fi ;;
    arch) ok "Arch Linux" ;;
    *)
      if [[ -n "$OS_FAMILY" ]]; then note "$id is not tested. It is like $OS_FAMILY, so the script treats it as $OS_FAMILY."
      else bad "$id is not supported. Use Ubuntu 22.04+, Debian 12+, Fedora 40+, RHEL/Rocky/Alma 9+ or Arch."; fi
      ;;
  esac
  [[ -n "$PKG" && -n "$OS_FAMILY" ]] || bad "No supported package manager (apt, dnf or pacman)."
  ARCH=$(uname -m)
  case "$ARCH" in
    x86_64 | aarch64) ok "CPU type $ARCH" ;;
    *) bad "CPU type $ARCH is not supported (x86_64 or aarch64)." ;;
  esac
  if command -v systemctl >/dev/null && [[ -d /run/systemd/system ]]; then ok "systemd"; else bad "No systemd. The script needs systemd (services, Caddy, nginx, Docker)."; fi
  command -v ss >/dev/null || note "No 'ss' command (iproute2). The script sees used ports, but not which program uses them."
  VIRT=$(systemd-detect-virt 2>/dev/null || true)
  [[ -n "$VIRT" ]] || VIRT=none
  if selinux_enforcing; then ok "SELinux is enforcing (the script asks before it changes a setting)"; fi
  return 0
}

# The code comes from GitHub and the images from GHCR. Neither has IPv6.
check_network() {
  if ! command -v curl >/dev/null; then note "No curl yet (the script installs it). Network not checked."; return; fi
  if curl -fsI --max-time 8 https://github.com >/dev/null 2>&1; then ok "github.com can be reached"
  else bad "github.com cannot be reached. On an IPv6-only server, turn on NAT64/DNS64 or add IPv4."; fi
  if curl -sI --max-time 8 https://ghcr.io/v2/ >/dev/null 2>&1; then ok "ghcr.io can be reached"
  else note "ghcr.io cannot be reached. Docker mode then builds the images here (10 minutes, 4 GB RAM)."; fi
}

check_resources() {
  local cpus free_gb disk=/var
  if ((IS_MAC)); then
    # macOS adds swap by itself. The Docker VM has its own memory limit (see check_docker).
    MEM_MB=$(($(sysctl -n hw.memsize) / 1024 / 1024))
    SWAP_MB=$MEM_MB
    cpus=$(sysctl -n hw.ncpu)
    disk="$HOME"
  else
    MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
    SWAP_MB=$(awk '/SwapTotal/ {print int($2/1024)}' /proc/meminfo)
    cpus=$(nproc)
  fi
  if ((MEM_MB < 1024)); then
    bad "RAM ${MEM_MB} MB. Zerodot needs 2 GB or more (swap can help)."
  elif ((MEM_MB < 2048)); then
    note "RAM ${MEM_MB} MB. Enough to run, tight to build (native mode builds). The script adds swap."
  else
    ok "RAM ${MEM_MB} MB, ${cpus} CPU"
  fi
  if ((MEM_MB < 3900 && SWAP_MB == 0)); then tip "Add swap before building (the script does this for you)."; fi
  free_gb=$(df -Pk "$disk" 2>/dev/null | awk 'NR==2 {print int($4/1024/1024)}')
  if ((free_gb < 4)); then bad "Disk: ${free_gb} GB free on $disk. Need 8 GB or more."
  elif ((free_gb < 8)); then note "Disk: ${free_gb} GB free on $disk. Docker images and data use about 6 GB."
  else ok "Disk: ${free_gb} GB free on $disk"; fi
  if [[ "$VIRT" == "openvz" || "$VIRT" == "lxc" ]]; then
    note "This server is a container ($VIRT). Docker may not work here."
    tip "Container VPS ($VIRT): use --native."
  fi
}

PORT_OWNER=""   # the program on port 80 or 443, empty when both are free
check_ports() {
  local who p
  for p in 80 443; do
    if port_in_use "$p"; then
      who=$(listener "$p")
      who="${who:-unknown}"
      # Caddy or nginx that systemd does not run (by hand, a panel, a container): not ours to change.
      if [[ "$who" == caddy || "$who" == nginx ]] && ! svc_active "$who"; then who="$who (not a systemd service)"; fi
      [[ -n "$PORT_OWNER" ]] || PORT_OWNER="$who"
      case "$who" in
        caddy) ok "Port $p is used by Caddy (the script can add a site to it)" ;;
        nginx) ok "Port $p is used by nginx (the script can add a site to it: --proxy nginx)" ;;
        docker-proxy)
          note "Port $p is used by a container (Traefik, Nginx Proxy Manager, Caddy in Docker...)."
          tip "Port $p belongs to a proxy in Docker: use --proxy none and add the upstream the script prints, or --proxy cloudflared."
          ;;
        *)
          note "Port $p is used by $who. Neither Caddy nor nginx can start next to it."
          tip "Port $p is taken by $who: use --proxy none (add the rule by hand) or --proxy cloudflared."
          ;;
      esac
    else
      ok "Port $p is free"
    fi
  done
}

check_docker() {
  if ! command -v docker >/dev/null 2>&1; then
    if ((IS_MAC)); then bad "Docker is not installed. Install Docker Desktop or OrbStack, start it, and run again."
    else note "Docker is not installed (the script can install it)."; fi
    return
  fi
  HAS_DOCKER=1
  local dv cv
  if [[ "$(docker --version 2>/dev/null || true)" == *[Pp]odman* ]]; then
    bad "'docker' is Podman (podman-docker). Zerodot needs Docker Engine. Use --native, or install Docker CE."
    return
  fi
  dv=$(docker version --format '{{.Server.Version}}' 2>/dev/null || true)
  if [[ -z "$dv" ]]; then
    if ((IS_MAC)); then bad "Docker is installed but does not answer. Start Docker Desktop or OrbStack, and run again."; return; fi
    note "Docker is installed but the service does not answer."
    tip "Start Docker (systemctl start docker) and run again. The script does not start it: that also starts your other containers."
    return
  fi
  if ((IS_MAC)); then
    # The containers run in a VM with its own memory limit.
    local vm_mb
    vm_mb=$(($(docker info --format '{{.MemTotal}}' 2>/dev/null || echo 0) / 1024 / 1024))
    if ((vm_mb > 0 && vm_mb < 3500)); then
      note "The Docker VM has ${vm_mb} MB RAM. Zerodot needs about 4 GB."
      tip "Give the Docker VM 4 GB or more (Docker Desktop: Settings > Resources)."
    fi
  fi
  cv=$(docker compose version --short 2>/dev/null | sed 's/^v//' || true)
  if [[ -z "$cv" ]]; then
    bad "Docker $dv has no Compose v2. Update Docker."
  elif ver_ge "$cv" 2.24.0; then
    ok "Docker $dv, Compose $cv"
    DOCKER_OK=1
  else
    bad "Docker Compose $cv is too old. Zerodot needs 2.24 or newer."
    tip "Update Docker: curl -fsSL https://get.docker.com | sh"
  fi
}

detect_postgres() {
  PG_STATE=none
  if [[ -n "${DATABASE_URL:-}" ]]; then PG_STATE=external; return; fi
  if port_in_use 5432 || [[ -S /var/run/postgresql/.s.PGSQL.5432 ]]; then
    PG_STATE=running
  elif command -v pg_lsclusters >/dev/null && [[ -n "$(pg_lsclusters -h 2>/dev/null)" ]]; then
    PG_STATE=installed
  elif command -v postgres >/dev/null || [[ -f /var/lib/pgsql/data/PG_VERSION || -f /var/lib/postgres/data/PG_VERSION ]]; then
    PG_STATE=installed
  elif command -v psql >/dev/null; then
    PG_STATE=client
  fi
  if [[ "$PG_STATE" == running ]] && id postgres >/dev/null 2>&1; then
    PG_VERNUM=$(cd / && runuser -u postgres -- psql -Atqc 'show server_version_num' 2>/dev/null || echo 0)
    PG_PORT=$(cd / && runuser -u postgres -- psql -Atqc 'show port' 2>/dev/null || echo 5432)
  fi
  return 0
}

report_postgres() {
  case "$PG_STATE" in
    external) ok "Postgres: using DATABASE_URL from the environment" ;;
    running)
      if ((PG_VERNUM >= 130000)); then
        ok "Postgres $((PG_VERNUM / 10000)) is running on this server (port $PG_PORT)"
        tip "Native mode can use this Postgres. It makes its own database and user. Other databases are not touched."
      elif ((PG_VERNUM > 0)); then
        bad "Postgres $((PG_VERNUM / 10000)) is too old. Zerodot needs 13 or newer."
        tip "Postgres is too old for native mode. Use Docker mode (it brings Postgres 17)."
      else
        note "Postgres is running but this script cannot log in as the postgres user."
        if ((IS_MAC)); then tip "To use the Postgres on this Mac, set DATABASE_URL=postgres://USER:PASS@localhost:5432/DB (else Docker brings one)."
        else tip "Native mode needs root access to Postgres. Set DATABASE_URL to use your own database."; fi
      fi
      ;;
    installed)
      note "Postgres is installed but not running."
      tip "Native mode does not start a stopped Postgres (it can be stopped on purpose). Start it, or set DATABASE_URL."
      ;;
    client) note "Only the Postgres client (psql) is installed." ;;
    *) ok "No Postgres on this server (Docker brings one; native mode installs one)" ;;
  esac
}

detect_redis() {
  RD_STATE=none; RD_CLI=""; RD_VERSION=""; RD_POLICY=""; RD_AUTH=0
  if [[ -n "${VALKEY_URL:-}" ]]; then RD_STATE=external; return; fi
  local c
  for c in valkey-cli redis-cli; do command -v "$c" >/dev/null && { RD_CLI="$c"; break; }; done
  if port_in_use 6379; then
    RD_STATE=running
    if [[ -n "$RD_CLI" ]]; then
      if [[ "$("$RD_CLI" -h 127.0.0.1 ping 2>&1 || true)" == *NOAUTH* ]]; then
        RD_AUTH=1
      else
        RD_VERSION=$("$RD_CLI" -h 127.0.0.1 info server 2>/dev/null | tr -d '\r' | grep -E '^(valkey_version|redis_version):' | head -1 | cut -d: -f2 || true)
        RD_POLICY=$("$RD_CLI" -h 127.0.0.1 config get maxmemory-policy 2>/dev/null | sed -n 2p | tr -d '\r' || true)
      fi
    fi
  elif command -v valkey-server >/dev/null || command -v redis-server >/dev/null; then
    RD_STATE=installed
  fi
  return 0
}

report_redis() {
  case "$RD_STATE" in
    external) ok "Valkey/Redis: using VALKEY_URL from the environment" ;;
    running)
      if ((RD_AUTH)); then
        note "Valkey/Redis is running on 6379 and needs a password."
        tip "Set VALKEY_URL=redis://:PASSWORD@127.0.0.1:6379/N to use it in native mode."
      else
        ok "Valkey/Redis ${RD_VERSION:-(version unknown)} is running on port 6379"
        [[ -n "$RD_POLICY" && "$RD_POLICY" != noeviction ]] && {
          note "It uses maxmemory-policy '$RD_POLICY'. The job queue needs 'noeviction' or jobs can vanish under memory pressure."
          tip "Set 'maxmemory-policy noeviction' in your Redis/Valkey config before native mode shares it."
        }
        if ((IS_MAC)); then tip "Docker mode can share this Valkey/Redis: --valkey host (own database number)."
        else tip "Native mode can share this Valkey/Redis, in its own database number."; fi
      fi
      ;;
    installed)
      note "Valkey/Redis is installed but not running."
      tip "Native mode does not start or change a stopped Valkey/Redis. Start it, or set VALKEY_URL."
      ;;
    *) ok "No Valkey/Redis on this server (Docker brings one; native mode installs one)" ;;
  esac
}

check_other() {
  if command -v caddy >/dev/null; then ok "Caddy $(caddy version 2>/dev/null | awk '{print $1}')"; else ok "No Caddy yet (the script can install it)"; fi
  if command -v nginx >/dev/null; then ok "nginx $(nginx -v 2>&1 | sed 's#.*/##')"; fi
  if unit_exists cloudflared.service; then ok "cloudflared runs a tunnel here (--proxy cloudflared adds to it)"; fi
  case "$(fw_name)" in
    ufw) ok "Firewall (ufw) is on: for Caddy or nginx the script allows 80 and 443" ;;
    firewalld) ok "Firewall (firewalld) is on: for Caddy or nginx the script allows http and https" ;;
    *)
      if ((IS_MAC == 0)); then
        note "No active firewall (ufw or firewalld)."
        tip "Turn on a firewall. Allow SSH first, then 80 and 443."
      fi
      ;;
  esac
  ((IS_MAC)) && return 0
  if command -v node >/dev/null; then ok "Node $(node -v) found (native mode may use a private Node if it does not fit)"; fi
}

preflight() {
  say "Checking this server"
  check_os
  check_network
  check_resources
  check_ports
  check_docker
  detect_postgres; report_postgres
  detect_redis; report_redis
  check_other
}

# The proxy to use when nobody says: the one that already has the ports, else Caddy.
default_proxy() {
  # macOS: Caddy comes from Homebrew. No Homebrew, or nginx on the ports: change no proxy.
  if ((IS_MAC)); then
    [[ "$ADDR" != local ]] && command -v brew >/dev/null && [[ -z "$PORT_OWNER" || "$PORT_OWNER" == caddy ]] && { echo caddy; return; }
    echo none; return
  fi
  case "$PORT_OWNER" in
    "" | caddy) echo caddy ;;
    nginx) echo nginx ;;
    *) echo none ;;
  esac
}

# ---------------------------------------------------------------------------
# Main flow: step 1, look around
# ---------------------------------------------------------------------------
if ((IS_MAC)); then
  # Docker Desktop and Homebrew belong to the user, and Homebrew refuses root.
  [[ $EUID -ne 0 ]] || die "On macOS, run without sudo: bash install.sh"
  [[ "$MODE" != native ]] || die "--native is for Linux only. On macOS, the script uses Docker."
  [[ "$PROXY_ARG" != nginx ]] || die "--proxy nginx is for Linux only. On macOS, use caddy, cloudflared or none."
  MODE=docker
elif ((CHECK == 0)); then
  [[ $EUID -eq 0 ]] || die "Run as root (use sudo)."
fi
# check_domain: lower case, no scheme, no trailing dot. An IP address gets a hint.
check_domain() {
  DOMAIN=$(printf '%s' "$DOMAIN" | tr '[:upper:]' '[:lower:]' | sed -E 's#^https?://##; s#/.*$##; s#\.$##')
  if [[ "$DOMAIN" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then
    # An IP address: the address question offers sslip.io (HTTPS) or plain HTTP.
    SERVER_IP="$DOMAIN"; DOMAIN=""; ADDR="${ADDR:-nodomain}"
    return 0
  fi
  # --local installs are named by their port: localhost:3000.
  [[ "$DOMAIN" =~ ^localhost:[0-9]+$ ]] && return 0
  [[ "$DOMAIN" == *:* ]] && die "Give the domain without a port: ${DOMAIN%%:*}"
  [[ "$DOMAIN" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z][a-z0-9-]*[a-z0-9]$ ]] \
    || die "'$DOMAIN' is not a domain name. Example: zerodot.example.com"
}
SERVER_IP=""
[[ -z "$DOMAIN" ]] || check_domain
if ((CHECK == 0)); then
  # One run at a time. macOS has no flock: mkdir is atomic, so a folder is the lock.
  if ((IS_MAC)); then
    mkdir "${TMPDIR:-/tmp}/zerodot-install.lock" 2>/dev/null \
      || die "Another run of install.sh is active. Wait for it to finish. (If none runs, remove ${TMPDIR:-/tmp}/zerodot-install.lock.)"
    LOCK_DIR="${TMPDIR:-/tmp}/zerodot-install.lock"
  else
    exec 9>/run/zerodot-install.lock
    flock -n 9 || die "Another run of install.sh is active. Wait for it to finish."
  fi
  trap on_exit EXIT
  # A command that fails without a message: say which one.
  set -E
  trap 'printf "%serror:%s this command failed (line %s): %s\n" "$R" "$N" "$LINENO" "$BASH_COMMAND" >&2' ERR
fi

init_tui
banner
preflight
scan_installs

if ((${#INSTALLS[@]} > 0)); then
  say "Zerodot installs on this server"
  i=1
  for d in "${INSTALLS[@]}"; do
    printf '  %d) %s   %s   %s   %s\n' "$i" "$d" "$(state_get "$d" DOMAIN)" "$(state_get "$d" MODE)" "$(install_status "$d")"
    i=$((i + 1))
  done
else
  say "No Zerodot install found on this server"
fi

# What would we recommend?
RECOMMEND=docker
RECOMMEND_WHY="Docker keeps Zerodot, Postgres and Valkey in their own containers. Simplest and the easiest to move."
if ((IS_MAC)); then
  RECOMMEND_WHY="macOS runs Zerodot in Docker (Docker Desktop or OrbStack)."
elif [[ "$VIRT" == "openvz" || "$VIRT" == "lxc" ]] && ((HAS_DOCKER == 0)); then
  RECOMMEND=native
  RECOMMEND_WHY="This server is a container ($VIRT); Docker often does not work in one."
elif ((PG_VERNUM >= 130000)) && [[ "$RD_STATE" == running ]] && ((RD_AUTH == 0)); then
  RECOMMEND_WHY="$RECOMMEND_WHY (Native would also work: Postgres and Valkey already run here.)"
fi

if ((CHECK)); then
  say "Result"
  printf '  Recommended mode: %s%s%s. %s\n' "$B" "$RECOMMEND" "$N" "$RECOMMEND_WHY"
  printf '  Proxy: %s%s%s (change with --proxy caddy|nginx|cloudflared|none).\n' "$B" "$(default_proxy)" "$N"
  if ((${#SUGGEST[@]} > 0)); then
    printf '\n  Tips:\n'
    for t in "${SUGGEST[@]}"; do printf '   - %s\n' "$t"; done
  fi
  printf '\n  %d problem(s), %d warning(s). Nothing was changed.\n\n' "$FAILS" "$WARNS"
  ((FAILS == 0)) || exit 1
  exit 0
fi

((FAILS == 0)) || die "Fix the problems marked ✘ above and run again."

# ---------------------------------------------------------------------------
# Timers: backups and updates. systemd on Linux, launchd on macOS.
# ---------------------------------------------------------------------------
# job_files KIND -> the files of the timer KIND (backup or update) of this instance.
job_files() {
  if ((IS_MAC)); then echo "$HOME/Library/LaunchAgents/io.zerodot.${NAME}-$1.plist"
  else echo "/etc/systemd/system/${NAME}-$1.service /etc/systemd/system/${NAME}-$1.timer"; fi
}
job_exists() { local f; for f in $(job_files "$1"); do [[ -f "$f" ]] && return 0; done; return 1; }
remove_job() {
  local f
  job_exists "$1" || return 0
  if ((IS_MAC)); then
    launchctl bootout "gui/$(id -u)/io.zerodot.${NAME}-$1" 2>/dev/null || true
  else
    systemctl disable --now "${NAME}-$1.timer" >/dev/null 2>&1 || true
  fi
  for f in $(job_files "$1"); do rm -f "$f"; done
  ((IS_MAC)) || systemctl daemon-reload
  changed "Removed the $1 timer of ${NAME}"
}
# add_job KIND WHEN HOUR DESCRIPTION COMMAND...: run COMMAND daily or weekly (Sunday) at HOUR.
add_job() {
  local kind="$1" when="$2" hour="$3" desc="$4" f cal
  shift 4
  if ((IS_MAC)); then
    local label="io.zerodot.${NAME}-${kind}" a plist_args=""
    f=$(job_files "$kind")
    for a in "$@"; do plist_args+="    <string>$(printf '%s' "$a" | sed 's/&/\&amp;/g; s/</\&lt;/g')</string>"$'\n'; done
    mkdir -p "$(dirname "$f")" "$HOME/Library/Logs"
    cat >"$f" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- ${desc}. Written by Zerodot install.sh. Run the script again to change it. -->
<plist version="1.0">
<dict>
  <key>Label</key><string>${label}</string>
  <key>ProgramArguments</key>
  <array>
${plist_args}  </array>
  <key>EnvironmentVariables</key>
  <dict><key>PATH</key><string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string></dict>
  <key>StartCalendarInterval</key>
  <dict><key>Hour</key><integer>${hour}</integer><key>Minute</key><integer>0</integer>$([[ $when == weekly ]] && echo '<key>Weekday</key><integer>0</integer>')</dict>
  <key>StandardOutPath</key><string>$HOME/Library/Logs/${NAME}-${kind}.log</string>
  <key>StandardErrorPath</key><string>$HOME/Library/Logs/${NAME}-${kind}.log</string>
</dict>
</plist>
PLIST
    launchctl bootout "gui/$(id -u)/${label}" 2>/dev/null || true
    launchctl bootstrap "gui/$(id -u)" "$f" || die "launchctl could not load $f."
  else
    local cmd="" a
    for a in "$@"; do cmd+=" $(printf '%q' "$a")"; done
    if [[ "$when" == weekly ]]; then cal="Sun *-*-* $(printf '%02d' "$hour"):00:00"; else cal="*-*-* $(printf '%02d' "$hour"):00:00"; fi
    cat >"/etc/systemd/system/${NAME}-${kind}.service" <<UNIT
# Written by Zerodot install.sh. Run the script again to change it.
[Unit]
Description=${desc}
After=network-online.target

[Service]
Type=oneshot
Environment=HOME=/root
ExecStart=${cmd# }
UNIT
    cat >"/etc/systemd/system/${NAME}-${kind}.timer" <<UNIT
# Written by Zerodot install.sh. Run the script again to change it.
[Unit]
Description=${desc} (${when})

[Timer]
OnCalendar=${cal}
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target
UNIT
    systemctl daemon-reload
    systemctl enable --now "${NAME}-${kind}.timer" >/dev/null 2>&1 || die "systemctl could not start ${NAME}-${kind}.timer."
  fi
  changed "${desc}: ${when} ($(job_files "$kind" | awk '{print $NF}'))"
}

# The backup script: the database (pg_dump, gzip) and a copy of .env, which holds the secret key.
write_backup_script() {
  local f="$1" dump
  if [[ "$MODE" == docker && "$PG_MODE" == docker ]]; then
    dump='docker compose exec -T postgres pg_dump -U zerodot zerodot'
  elif [[ "$MODE" == docker ]]; then
    # From the network of the install: Postgres on this server lets that network in.
    dump='docker run --rm --network "$(docker compose config 2>/dev/null | sed -n "s/^name: //p" | head -1)_default" --add-host host.docker.internal:host-gateway postgres:17 pg_dump "$url"'
  else
    dump='pg_dump "$url"'
  fi
  cat >"$f" <<SCRIPT
#!/usr/bin/env bash
# Back up Zerodot (${NAME}): the database and .env. Written by install.sh. Run the script again to change it.
# Restore: gunzip -c FILE.sql.gz | psql "\$DATABASE_URL"   (Docker: docker compose exec -T postgres psql -U zerodot zerodot)
set -euo pipefail
dir=$(printf '%q' "$DIR")
out=$(printf '%q' "$BACKUP_DIR")
keep=${BACKUP_KEEP}
cd "\$dir"
url=\$(grep -m1 '^DATABASE_URL=' .env | cut -d= -f2- || true)
umask 077
mkdir -p "\$out"
[[ -d "\$out" && -w "\$out" ]] || { echo "Backup folder \$out is not a folder you can write to." >&2; exit 1; }
# Never overwrite a backup. The .part file is made with noclobber, so two backups at the same time get -2, -3 ...
stamp=\$(date +%Y%m%d-%H%M%S); n=1
file="\$out/${NAME}-\$stamp.sql.gz"
until [[ ! -e "\$file" ]] && (set -o noclobber; : >"\$file.part") 2>/dev/null; do
  [[ -e "\$file" || -e "\$file.part" ]] || { echo "Cannot make a backup file in \$out." >&2; exit 1; }
  n=\$((n + 1))
  ((n <= 100)) || { echo "Too many backups with the same name in \$out." >&2; exit 1; }
  file="\$out/${NAME}-\$stamp-\$n.sql.gz"
done
trap 'rm -f "\$file.part"' ERR
${dump} | gzip >"\$file.part"
mv "\$file.part" "\$file"
cp .env "\$out/${NAME}.env"
cp .env "\${file%.sql.gz}.env"
# Keep the newest \$keep.
ls -1t "\$out"/${NAME}-*.sql.gz | tail -n +\$((keep + 1)) | while IFS= read -r old; do rm -f "\$old" "\${old%.sql.gz}.env"; done
echo "Backup: \$file"
SCRIPT
  chmod 700 "$f"
}

# Backups and updates as chosen. Off removes the timer.
setup_jobs() {
  local script cli
  if [[ "$BACKUP" == off ]]; then
    remove_job backup
  else
    if ((IS_MAC)); then script="$HOME/.zerodot/${NAME}-backup.sh"; else script="/usr/local/sbin/${NAME}-backup"; fi
    mkdir -p "$(dirname "$script")" "$BACKUP_DIR"
    chmod 700 "$BACKUP_DIR"
    write_backup_script "$script"
    [[ "$MODE" == docker ]] || command -v pg_dump >/dev/null || pkg_install "$(pkgs_pg_client)" \
      || note "No pg_dump on this server. Install the Postgres client, or the backups fail."
    add_job backup "$BACKUP" 3 "Zerodot backup (${NAME})" "$script"
    ok "Backups: ${BACKUP}, newest ${BACKUP_KEEP} kept in ${BACKUP_DIR}. Now: $script"
  fi
  if [[ "$AUTO_UPDATE" == off ]]; then
    remove_job update
  else
    # The timer runs the installed zerodot command (a copy owned by root). It gets the newest installer first.
    # No copy (an old checkout without scripts/zerodot): use install.sh.
    cli=$(cli_path)
    if [[ -f "$cli" ]]; then
      add_job update "$AUTO_UPDATE" 4 "Zerodot update (${NAME})" \
        "$(command -v bash)" "$cli" update "$DIR" --yes --no-tui
    else
      add_job update "$AUTO_UPDATE" 4 "Zerodot update (${NAME})" \
        "$(command -v bash)" "$DIR/scripts/install.sh" "$DOMAIN" --update --yes --no-tui
    fi
    ok "Updates: ${AUTO_UPDATE}$([[ -n $VERSION ]] && echo " (stays on release $VERSION until you give another --version)")"
  fi
}

# The zerodot command: a copy of scripts/zerodot in the PATH. A copy, not a link: root runs it,
# and the folder of a native install belongs to the service user.
cli_path() {
  local d
  if ((IS_MAC == 0)); then echo /usr/local/bin/zerodot; return 0; fi
  for d in /opt/homebrew/bin /usr/local/bin; do
    [[ -f "$d/zerodot" && -w "$d/zerodot" ]] && { echo "$d/zerodot"; return 0; }
  done
  for d in /opt/homebrew/bin /usr/local/bin; do
    [[ -d "$d" && -w "$d" ]] && { echo "$d/zerodot"; return 0; }
  done
  echo "$HOME/.local/bin/zerodot"
}
install_cli() {
  local src="$DIR/scripts/zerodot" dest
  if [[ ! -f "$src" ]]; then
    note "This release has no zerodot command. It comes with release 0.2.31 and newer."
    return 0
  fi
  dest=$(cli_path)
  # Root runs the copy. Native mode: the service user owns the folder and could change the file.
  # Copy only the file as the release has it.
  if ((IS_MAC == 0)) && [[ -n "$(git -c safe.directory="$DIR" -C "$DIR" status --porcelain -- scripts/zerodot 2>/dev/null || echo changed)" ]]; then
    note "$src has local changes. The zerodot command was not updated."
    return 0
  fi
  mkdir -p "$(dirname "$dest")"
  if [[ -f "$dest" && ! -L "$dest" ]] && cmp -s "$src" "$dest"; then
    ok "The zerodot command: $dest"
    return 0
  fi
  rm -f "$dest"  # an old link, or an older copy
  if ((IS_MAC)); then
    cp "$src" "$dest" && chmod 755 "$dest"
  else
    install -o root -g root -m 755 "$src" "$dest"
  fi
  changed "The zerodot command: $dest"
  ok "The zerodot command: $dest"
  case ":$PATH:" in
    *":$(dirname "$dest"):"*) ;;
    *) note "Add $(dirname "$dest") to your PATH to use the zerodot command." ;;
  esac
}
# other_installs: how many Zerodot installs, other than $DIR, are on this server.
other_installs() {
  local d n=0 real
  real=$(readlink -f "$DIR" 2>/dev/null || echo "$DIR")
  for d in "${INSTALLS[@]}"; do
    [[ "$(readlink -f "$d" 2>/dev/null || echo "$d")" == "$real" ]] || n=$((n + 1))
  done
  echo "$n"
}

# --uninstall: stop and remove the services. The data, the folder and the proxy site stay.
uninstall_instance() {
  local proxy="$1" dbname="${NAME//-/_}" project data_dir backup_dir url saved conf pg_mode rd_mode
  is_zerodot_dir "$DIR" || die "$DIR does not look like a Zerodot install. Nothing was changed."
  project=$(compose_project "$DIR")
  pg_mode=$(state_get "$DIR" PG_MODE); pg_mode="${pg_mode:-docker}"
  rd_mode=$(state_get "$DIR" RD_MODE); rd_mode="${rd_mode:-docker}"
  data_dir=$(state_get "$DIR" DATA_DIR)
  backup_dir=""
  [[ ! "$(state_get "$DIR" BACKUP)" =~ ^(daily|weekly)$ ]] || backup_dir=$(state_get "$DIR" BACKUP_DIR)
  url=$(grep -m1 '^DATABASE_URL=' "$DIR/.env" 2>/dev/null | cut -d= -f2- || true)
  say "Uninstall ${NAME}: $DIR ($DOMAIN, $MODE)"
  if [[ -z "$PURGE" ]]; then
    choose "Uninstall" "What do you want to remove?" keep \
      keep "The services only. Keep the data and the folder, to install again later" \
      all "Everything: services, database, files and the folder. Cannot be undone"
    if [[ "$REPLY" == all ]]; then PURGE=1; else PURGE=0; fi
  fi
  if ((PURGE)); then
    cat <<EOM
  This stops Zerodot and removes its services$([[ $MODE == docker ]] && echo ", containers and volumes"), the timers,
  $([[ $MODE == native ]] && echo "the files in /var/lib/${NAME}, the user ${NAME}, ")the folder $DIR${data_dir:+ and $data_dir}.
  All workflows, runs, credentials and files of this instance are lost. A copy of .env stays in your home folder.
EOM
  else
    cat <<EOM
  This stops Zerodot and removes its services$([[ $MODE == docker ]] && echo " (containers)"), backup and update timers.
  It keeps the folder, .env, the database, the files and the proxy site.
EOM
  fi
  if ((YES == 0 && DONE == 1 && REINSTALL == 0)) && have_tty; then
    # Ask again until the name is right. q stops.
    while true; do
      ask "Type ${NAME} to remove it, or q to stop: " ""
      [[ "$REPLY" == "$NAME" ]] && break
      [[ "$REPLY" == q || "$REPLY" == Q ]] && { echo "Stopped. Nothing was changed."; exit 0; }
      [[ -z "$REPLY" ]] || echo "  That is not ${NAME}."
    done
  fi
  remove_job backup
  remove_job update
  if ((IS_MAC)); then rm -f "$HOME/.zerodot/${NAME}-backup.sh"; else rm -f "/usr/local/sbin/${NAME}-backup"; fi
  if ((PURGE)) && (($(other_installs) == 0)); then
    # The last install: the zerodot command goes too.
    for link in /usr/local/bin/zerodot /opt/homebrew/bin/zerodot "$HOME/.local/bin/zerodot"; do
      if [[ -f "$link" ]] && grep -q 'zerodot: manage a Zerodot install' "$link" 2>/dev/null; then
        rm -f "$link"
        changed "Removed the zerodot command $link"
      fi
    done
  fi
  if [[ "$MODE" == docker ]]; then
    if ((PURGE)); then
      (cd "$DIR" && docker compose down --volumes --remove-orphans) || die "docker compose down failed in $DIR."
      changed "Removed the containers and the volumes of ${NAME}"
    else
      (cd "$DIR" && docker compose down --remove-orphans) || die "docker compose down failed in $DIR."
      changed "Removed the containers of ${NAME} (the volumes stay)"
    fi
  else
    systemctl disable --now "${NAME}-web" "${NAME}-api" "${NAME}-worker" "${NAME}-sandbox" >/dev/null 2>&1 || true
    rm -f "/etc/systemd/system/${NAME}-"{web,api,worker,sandbox}.service
    systemctl daemon-reload
    changed "Removed the services ${NAME}-web, -api, -worker and -sandbox"
  fi

  if ((PURGE == 0)); then
    say "Done. To remove the rest (this cannot be undone):"
    echo "  Run the script again with --uninstall --purge, or do it by hand."
    echo "  First keep a copy of $DIR/.env: it holds the key of the saved credentials."
    if [[ "$MODE" == docker ]]; then
      echo "  Data:    docker volume rm ${project}_postgres-data ${project}_valkey-data ${project}_blob-data ${project}_node-packages"
    else
      echo "  Data:    runuser -u postgres -- dropdb ${dbname} && runuser -u postgres -- dropuser ${dbname}"
      echo "           rm -rf /var/lib/${NAME} && userdel ${NAME}"
    fi
    [[ -z "$data_dir" ]] || echo "           rm -rf $data_dir"
    echo "  Folder:  rm -rf $DIR"
  else
    # The key of the saved credentials: keep a copy, in case the database has a backup somewhere.
    saved="$HOME/${NAME}.env.removed-$(date +%Y%m%d%H%M%S)"
    (umask 077 && cp "$DIR/.env" "$saved") && ok "Copy of .env: $saved"
    # A database that the script made on this server: a user and a database named after the instance.
    if [[ "$url" =~ ^postgres(ql)?://${dbname}:[^@]*@(127\.0\.0\.1|localhost|host\.docker\.internal):[0-9]+/${dbname}(\?|$) ]] && ((IS_MAC == 0)); then
      if runuser -u postgres -- dropdb --if-exists "$dbname" && runuser -u postgres -- dropuser --if-exists "$dbname"; then
        changed "Postgres: removed the database and the user ${dbname}"
      else
        note "Cannot remove the Postgres database ${dbname}. Remove it by hand: dropdb ${dbname}; dropuser ${dbname}"
      fi
    elif [[ -n "$url" ]] && [[ "$MODE" == native || "$pg_mode" != docker ]]; then
      note "The database is not one that the script made. It stays: ${url%%@*}@..."
    fi
    if [[ "$MODE" == native ]]; then
      rm -rf "/var/lib/${NAME}"
      id "$NAME" >/dev/null 2>&1 && userdel "$NAME" 2>/dev/null && changed "Removed the system user ${NAME}"
    fi
    [[ -z "$data_dir" ]] || { rm -rf "$data_dir"; changed "Removed $data_dir"; }
    # An nginx site that the script wrote. A site edited by certbot still has the first line.
    for conf in "/etc/nginx/sites-available/${NAME}.conf" "/etc/nginx/conf.d/${NAME}.conf"; do
      if [[ -f "$conf" ]] && head -1 "$conf" | grep -q "^# Written by Zerodot install.sh (${NAME})"; then
        rm -f "$conf" "/etc/nginx/sites-enabled/${NAME}.conf"
        changed "nginx: removed the site $conf"
        nginx -t >/dev/null 2>&1 && systemctl reload nginx 2>/dev/null || note "nginx -t fails after the site was removed. Look at nginx."
      fi
    done
    rm -rf "$DIR"
    rm -f "/etc/zerodot/${NAME}.state"
    changed "Removed $DIR"
    say "Done. ${NAME} is removed."
    [[ "$MODE" == docker && "$rd_mode" == docker ]] || echo "  Valkey/Redis outside Docker: the keys of ${NAME} stay in its database."
  fi
  ((REINSTALL)) && return 0
  case "$proxy" in
    caddy) echo "  Proxy:   remove the ${DOMAIN} block from $CADDYFILE, then reload Caddy" ;;
    nginx) ((PURGE)) || echo "  Proxy:   rm /etc/nginx/sites-*/${NAME}.conf /etc/nginx/conf.d/${NAME}.conf, then: systemctl reload nginx" ;;
    cloudflared) echo "  Proxy:   remove the public hostname ${DOMAIN} from your tunnel in Cloudflare" ;;
  esac
  [[ -z "$backup_dir" ]] || echo "  Backups: $backup_dir (kept. Remove by hand when you do not need them.)"
  ((PURGE)) || echo "  To install again: bash $DIR/scripts/install.sh ${DOMAIN}"
}

# The questions of "More settings". Each answer is like the option of the same name.
more_settings() {
  local def
  input "Port" "Port of the app on this server. The proxy sends the traffic to it.\nEmpty: the first free port from 3000." "$PORT_ARG"
  if [[ -n "$REPLY" ]]; then valid_port "$REPLY" || die "'$REPLY' is not a port number."; PORT_ARG="$REPLY"; fi
  input "Admin emails" "Instance admins, comma separated. They can sign up when signup is off.\nEmpty: the first user who signs up is the admin." "$(env_value ZERODOT_ADMIN_EMAILS)"
  [[ -z "$REPLY" ]] || ENV_SETS+=("ZERODOT_ADMIN_EMAILS=$REPLY")
  if [[ -n "$(env_value ZERODOT_ADMIN_EMAILS)" ]]; then
    def=open; [[ "$(env_value ZERODOT_SIGNUP_DISABLED)" == true ]] && def=closed
    choose "Signup" "Who can make an account?" "$def" \
      open "Anyone who opens the address" \
      closed "Only the admin emails and invited people"
    if [[ "$REPLY" == closed ]]; then ENV_SETS+=(ZERODOT_SIGNUP_DISABLED=true); else ENV_SETS+=(ZERODOT_SIGNUP_DISABLED=false); fi
  fi
  input "Files folder" "Turns on the Read/Write Files node. Workflows reach only this folder.\nUse a folder outside the install and outside a web root, for example /var/lib/${NAME:-zerodot}/files.\nEmpty: the node stays off." "$FILES_DIR_ARG"
  if [[ -n "$REPLY" ]]; then
    [[ "$REPLY" == /* ]] || die "'$REPLY' is not a full path (it starts with /)."
    case "$REPLY" in
      / | /etc* | /usr* | /bin* | /sbin* | /boot* | /proc* | /sys* | /dev* | /root* | /var/www*) die "$REPLY is not a safe folder for files." ;;
    esac
    FILES_DIR_ARG="${REPLY%/}"
  fi
  input "Version" "Release to install, for example 0.2.25. Updates stay on it.\nlatest: the newest release; updates follow new releases." "${VERSION_ARG:-latest}"
  VERSION_ARG="${REPLY#v}"
  [[ "$VERSION_ARG" == latest || "$VERSION_ARG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || die "'$REPLY' is not a release such as 0.2.25."
  choose "Backups" "Back up the database and .env by itself?" "${BACKUP_ARG:-off}" \
    off "No" daily "Every day at about 03:00" weekly "Every Sunday at about 03:00"
  BACKUP_ARG="$REPLY"
  choose "Updates" "Update this install by itself?" "${AUTO_UPDATE_ARG:-off}" \
    off "No, I run the script" daily "Every day at about 04:00" weekly "Every Sunday at about 04:00"
  AUTO_UPDATE_ARG="$REPLY"
}

# ---------------------------------------------------------------------------
# Step 2: update an install, or set up a new instance?
# ---------------------------------------------------------------------------
TARGET=""
ASKED=0
ACTION_ARG="$ACTION"
MODE_ARG="$MODE"; PG_ARG="$PG_MODE"; RD_ARG="$RD_MODE"
((UNINSTALL == 0)) || ACTION=update
if ((${#INSTALLS[@]} > 0)); then
  if [[ -n "$DOMAIN" && "$ACTION" != new ]]; then
    for d in "${INSTALLS[@]}"; do
      [[ "$(state_get "$d" DOMAIN)" == "$DOMAIN" ]] && { TARGET="$d"; ACTION=update; }
    done
  fi
  if [[ -z "$ACTION" ]]; then
    ASKED=1
    if ((YES)) || ! have_tty; then
      if [[ -z "$DOMAIN" && ${#INSTALLS[@]} -eq 1 ]]; then ACTION=update; TARGET="${INSTALLS[0]}"; else ACTION=new; fi
    elif ((TUI)); then
      tui_menu "Zerodot is already installed" "Found ${#INSTALLS[@]} install(s) on this server.\nWhat do you want to do?" \
        u "Update an install that exists" \
        s "Set up an install again (removes its data; pick Recommended or Advanced)" \
        n "Set up another instance on this server" \
        r "Uninstall an install"
      case "$REPLY" in u) ACTION=update ;; s) ACTION=update; REINSTALL=1 ;; r) ACTION=update; UNINSTALL=1 ;; *) ACTION=new ;; esac
    else
      printf '\nWhat do you want to do?\n  u) Update an install that exists\n  s) Set up an install again (removes its data; pick Recommended or Advanced)\n  n) Set up another instance on this server\n  r) Uninstall an install\n  q) Quit\n'
      ask "Choose [u/s/n/r/q]: " "u"
      case "$REPLY" in
        [Uu]*) ACTION=update ;;
        [Ss]*) ACTION=update; REINSTALL=1 ;;
        [Nn]*) ACTION=new ;;
        [Rr]*) ACTION=update; UNINSTALL=1 ;;
        *) echo "Stopped. Nothing was changed."; exit 0 ;;
      esac
    fi
  fi
  if [[ "$ACTION" == update && -z "$TARGET" ]]; then
    if ((${#INSTALLS[@]} == 1)); then
      TARGET="${INSTALLS[0]}"
    elif ((YES)) || ! have_tty; then
      die "More than one install found. Give the domain of the one to $( ((UNINSTALL)) && echo uninstall || echo update), for example: install.sh zerodot.example.com"
    else
      if ((TUI)); then
        items=()
        i=1
        for d in "${INSTALLS[@]}"; do
          items+=("$i" "$d  $(state_get "$d" DOMAIN)  $(state_get "$d" MODE)  $(install_status "$d")")
          i=$((i + 1))
        done
        if ((UNINSTALL)); then tui_menu "Uninstall which install?" "Pick the install to uninstall." "${items[@]}"
        elif ((REINSTALL)); then tui_menu "Set up which install again?" "Pick the install to remove and set up again." "${items[@]}"
        else tui_menu "Update which install?" "Pick the install to update." "${items[@]}"; fi
      else
        ask "Which install do you want to $( ((UNINSTALL)) && echo uninstall || { ((REINSTALL)) && echo 'set up again'; } || echo update)? [1-${#INSTALLS[@]}]: " "$( ((UNINSTALL || REINSTALL)) || echo 1)"
      fi
      [[ "$REPLY" =~ ^[0-9]+$ ]] && ((REPLY >= 1 && REPLY <= ${#INSTALLS[@]})) || die "Not a valid choice."
      TARGET="${INSTALLS[$((REPLY - 1))]}"
    fi
  fi
else
  ((UNINSTALL == 0)) || die "--uninstall given but no Zerodot install was found."
  [[ "$ACTION" == update ]] && die "--update given but no Zerodot install was found."
  ACTION=new
fi

if [[ "$ACTION" == update ]]; then
  DIR="$TARGET"
  NAME=$(state_get "$DIR" NAME)
  MODE=$(state_get "$DIR" MODE)
  STORED_DOMAIN=$(state_get "$DIR" DOMAIN)
  SCHEME=$(state_get "$DIR" SCHEME)
  [[ -n "$DOMAIN" && "$DOMAIN" != "$STORED_DOMAIN" ]] && die "This install uses $STORED_DOMAIN. To use $DOMAIN, set up another instance (--new)."
  DOMAIN="$STORED_DOMAIN"
  [[ -n "$DOMAIN" ]] || die "Cannot find the domain of $DIR (no ZERODOT_BASE_URL in its .env)."
  # Installs from before these settings used Caddy (or no proxy) and the database containers.
  STORED_PROXY=$(state_get "$DIR" PROXY)
  # Installs from before this key finished.
  DONE=$(state_get "$DIR" DONE); DONE="${DONE:-1}"
  # The domain of an install was given, so no menu yet: update, set up again or uninstall?
  # --recommended, --advanced or another mode on an install: the person wants to set it up again.
  def=update
  [[ -z "$SETUP" && ( -z "$MODE_ARG" || "$MODE_ARG" == "$MODE" ) ]] || def=again
  if [[ $def == again ]] && { ((YES)) || ! have_tty; }; then
    die "$DIR is a $MODE install. To set it up again (this removes its data), run the script on a terminal and pick 'Set up again'. To update it, leave out --recommended, --advanced, --docker and --native."
  fi
  if ((ASKED == 0 && UNINSTALL == 0)) && [[ -z "$ACTION_ARG" ]] && ((YES == 0)) && have_tty; then
    if ((DONE)); then
      choose "$NAME is installed" "$DIR ($DOMAIN, $MODE, $(install_status "$DIR")). What do you want to do?" "$def" \
        update "Update - keep the settings and the data" \
        again "Set up again - remove it (data too), then pick Recommended or Advanced" \
        uninstall "Uninstall"
    else
      choose "$NAME did not finish" "The last install in $DIR ($DOMAIN, $MODE) stopped before it finished. What do you want to do?" again \
        again "Start again - pick Recommended or Advanced" \
        update "Continue - the same settings ($MODE)" \
        uninstall "Uninstall"
    fi
    case "$REPLY" in again) REINSTALL=1 ;; uninstall) UNINSTALL=1 ;; esac
  fi
  if ((UNINSTALL)); then uninstall_instance "${STORED_PROXY:-caddy}"; exit 0; fi
  if ((REINSTALL)); then
    # Keep the port, so a proxy site for this domain still points to the app.
    PORT_ARG="${PORT_ARG:-$(state_get "$DIR" "$([[ $MODE == docker ]] && echo PORT || echo WEB_PORT)")}"
    # The old install is removed after the plan is accepted. Until then nothing changes.
    PURGE=1; OLD_MODE="$MODE"; OLD_PROXY="${STORED_PROXY:-caddy}"; OLD_NAME="$NAME"; OLD_DIR="$DIR"
    # A new install with the same domain. Enter keeps the name and the folder.
    input "Instance name" "Name of the new install. Used for the folder, the services and the database.\nLower-case letters, digits and '-'." "$NAME"
    NAME="${REPLY:-$NAME}"
    [[ "$NAME" =~ ^[a-z][a-z0-9-]{0,30}$ ]] || die "Name '$NAME' is not valid. Use lower-case letters, digits and '-'."
    left=()
    for d in "${INSTALLS[@]}"; do [[ "$d" == "$DIR" ]] || left+=("$d"); done
    INSTALLS=(${left[@]+"${left[@]}"})
    ACTION=new
    DONE=0
    [[ "$NAME" != "$OLD_NAME" ]] || DIR_ARG="${DIR_ARG:-$DIR}"
    MODE="$MODE_ARG"; PG_MODE="$PG_ARG"; RD_MODE="$RD_ARG"
    # macOS local install: DOMAIN is localhost:PORT. The new install makes it again.
    if [[ "$DOMAIN" == localhost* ]]; then DOMAIN=""; ADDR=local; PROXY_ARG=none; fi
  fi
fi
if [[ "$ACTION" == update ]]; then
  PROXY="${PROXY_ARG:-${STORED_PROXY:-$(default_proxy)}}"
  if [[ -n "$STORED_PROXY" && "$PROXY" != "$STORED_PROXY" ]]; then
    tip "The proxy changed from $STORED_PROXY to $PROXY. The old $STORED_PROXY site for $DOMAIN stays. Remove it by hand."
  fi
  if [[ "$MODE" == docker ]]; then
    for kind in PG RD; do
      stored=$(state_get "$DIR" "${kind}_MODE"); stored="${stored:-docker}"
      wanted="$([[ $kind == PG ]] && echo "$PG_MODE" || echo "$RD_MODE")"
      [[ -z "$wanted" || "$wanted" == "$stored" || "$stored" == url ]] \
        || die "This install keeps its $([[ $kind == PG ]] && echo Postgres || echo Valkey) in '$stored'. The script does not move data. See https://zerodot.io/docs/backup-and-move"
      if [[ $kind == PG ]]; then PG_MODE="$stored"; else RD_MODE="$stored"; fi
    done
  fi
  say "Updating $DIR ($DOMAIN, $MODE, proxy $PROXY)"
else
  DONE=0
  # 0. Recommended or advanced. --yes and no terminal: recommended.
  if [[ -z "$SETUP" ]]; then
    choose "Setup" "How much do you want to choose?" recommended \
      recommended "Recommended - give the address, the script picks the rest" \
      advanced "Advanced - choose mode, proxy, database, port, admins, backups..."
    SETUP="$REPLY"
  fi

  # 1. Address.
  if [[ -n "$DOMAIN" ]]; then
    ADDR=domain
  else
    if [[ -z "$ADDR" || "$ADDR" == nodomain ]]; then
      def=domain; [[ "$ADDR" == nodomain ]] && def=sslip
      opts=()
      # macOS: most installs are for this computer only.
      if ((IS_MAC)); then
        [[ "$ADDR" == nodomain ]] || def=local
        opts+=(local "Only this computer: http://localhost. No proxy, nothing open to the network.")
      fi
      ((YES)) && [[ -z "$ADDR" ]] && ((IS_MAC == 0)) && die "Give a domain, or --no-domain (sslip.io with HTTPS), or --ip (plain HTTP)."
      choose "Address" "How do people open this instance?" "$def" "${opts[@]}" \
        domain "My domain (example: zerodot.example.com). HTTPS." \
        sslip "No domain: <server-ip>.sslip.io. HTTPS, works at once." \
        ip "No domain: the server IP over plain HTTP. Tests only, not secure."
      ADDR="$REPLY"
    fi
    case "$ADDR" in
      domain)
        if ((TUI)); then
          tui_input "Domain" "Public address of this instance.\nPoint its DNS A record to this server first.\nExample: zerodot.example.com" ""
        else
          ask "Domain (example: zerodot.example.com): " ""
        fi
        DOMAIN="$REPLY"
        [[ -n "$DOMAIN" ]] || die "A domain is needed (example: zerodot.example.com)."
        check_domain
        [[ -n "$DOMAIN" ]] || die "That is an IP address. Pick a no-domain option instead."
        ;;
      sslip | ip)
        SERVER_IP="${SERVER_IP:-$(public_ip)}"
        if [[ -z "$SERVER_IP" ]]; then
          ask "Public IPv4 address of this server: " ""
          SERVER_IP="$REPLY"
        fi
        [[ "$SERVER_IP" =~ ^[0-9]+(\.[0-9]+){3}$ ]] || die "Cannot find the public IPv4 address. Give it: install.sh <ip> --ip"
        if [[ "$ADDR" == sslip ]]; then DOMAIN="${SERVER_IP//./-}.sslip.io"; else DOMAIN="$SERVER_IP"; SCHEME=http; fi
        ;;
      local)
        # The port comes later (docker_mode). Then DOMAIN becomes localhost:PORT.
        DOMAIN=localhost; SCHEME=http; PROXY_ARG=none
        ;;
      *) die "Unknown address choice '$ADDR'." ;;
    esac
  fi
  for d in "${INSTALLS[@]}"; do
    [[ "$(state_get "$d" DOMAIN)" == "$DOMAIN" ]] && die "$DOMAIN is already used by $d."
  done

  # Recommended: from here on, each question takes its default answer. Options still win.
  [[ "$SETUP" == advanced ]] || AUTO=1

  # 2. Name.
  if [[ -z "$NAME" ]]; then
    if ((${#INSTALLS[@]} == 0)); then NAME=zerodot
    elif [[ "$ADDR" == local ]]; then NAME=zerodot-local
    else NAME="zerodot-${DOMAIN%%.*}"; NAME="${NAME//[^a-z0-9-]/-}"; fi
    # Skip names that Docker or a folder already uses: zerodot, zerodot-2, zerodot-3...
    if [[ -z "$DIR_ARG" ]] && name_taken "$NAME"; then
      base="$NAME"; n=2
      while name_taken "${base}-${n}" && ((n < 50)); do n=$((n + 1)); done
      NAME="${base}-${n}"
    fi
    if ((AUTO)); then :
    elif ((TUI)); then
      ((YES)) || tui_input "Instance name" "Used for the folder, the services and the database.\nLower-case letters, digits and '-'." "$NAME"
      ((YES)) || NAME="$REPLY"
    else
      ask "Name of this instance [$NAME]: " "$NAME"
      NAME="$REPLY"
    fi
  fi
  [[ "$NAME" =~ ^[a-z][a-z0-9-]{0,30}$ ]] || die "Name '$NAME' is not valid. Use lower-case letters, digits and '-'."
  if ((IS_MAC)); then DIR="${DIR_ARG:-$HOME/$NAME}"; else DIR="${DIR_ARG:-/var/www/$NAME}"; fi
  if [[ -e "$DIR" && "$DIR" != "${OLD_DIR:-}" ]]; then
    is_zerodot_dir "$DIR" && die "$DIR is already a Zerodot install. Use --update, or pick another --name."
    [[ -z "$(ls -A "$DIR" 2>/dev/null)" ]] || die "$DIR exists and is not empty."
  fi

  # 3. Mode.
  if [[ -z "$MODE" ]]; then
    d_label="Docker - containers for Zerodot (and Postgres, Valkey if you want)"
    n_label="Native - no Docker; systemd services on this server"
    [[ "$RECOMMEND" == docker ]] && d_label="$d_label  (recommended)" || n_label="$n_label  (recommended)"
    choose "How do you want to run Zerodot?" "$RECOMMEND_WHY" "$RECOMMEND" docker "$d_label" native "$n_label"
    MODE="$REPLY"
  fi
  [[ "$ADDR" != local || "$MODE" == docker ]] || die "--local is for Docker mode."

  # 4. Proxy. A tunnel needs a domain in your Cloudflare account.
  PROXY="$PROXY_ARG"
  if [[ -z "$PROXY" ]]; then
    PROXY=$(default_proxy)
    opts=(caddy "Caddy - $([[ $SCHEME == https ]] && echo 'automatic HTTPS. ' || true)Installed if missing$( ((IS_MAC)) && echo ' (Homebrew)' || true)")
    ((IS_MAC)) || opts+=(nginx "nginx - a site in nginx$([[ $SCHEME == https ]] && echo ', HTTPS from certbot' || true)")
    [[ "$ADDR" == domain ]] && opts+=(cloudflared "Cloudflare Tunnel - no open ports, HTTPS from Cloudflare")
    opts+=(none "None - change no proxy; print the upstream for yours")
    choose "Proxy" "Who receives the web traffic? Ports 80 and 443: ${PORT_OWNER:-free}." "$PROXY" "${opts[@]}"
    PROXY="$REPLY"
  fi
  [[ "$PROXY" != cloudflared || "$ADDR" == domain ]] || die "A Cloudflare Tunnel needs a domain in your Cloudflare account."

  # 5 and 6. Database and queue.
  if [[ -n "${DATABASE_URL:-}" ]]; then
    PG_CHOICE=url
  else
    opts=()
    [[ "$MODE" == docker ]] && opts+=(docker "Own Postgres 17 container")
    ((PG_VERNUM >= 130000)) && opts+=(host "Postgres $((PG_VERNUM / 10000)) on this server - new database and user")
    [[ "$MODE" == native && "$PG_STATE" == none ]] && opts+=(install "Install Postgres on this server")
    opts+=(url "Another Postgres - I give a DATABASE_URL")
    def="${opts[0]}"
    [[ -n "$PG_MODE" ]] && def="$PG_MODE"
    if [[ -n "$PG_MODE" ]]; then REPLY="$PG_MODE"; else choose "Postgres" "Where does the database run?" "$def" "${opts[@]}"; fi
    PG_CHOICE="$REPLY"
    if [[ "$PG_CHOICE" == url ]]; then
      ((YES)) && die "Set DATABASE_URL to use another Postgres."
      if ((TUI)); then tui_input "DATABASE_URL" "postgres://user:password@host:5432/database?sslmode=require\nURL-encode special characters in the password." ""; else ask "DATABASE_URL: " ""; fi
      [[ "$REPLY" == postgres://* || "$REPLY" == postgresql://* ]] || die "That is not a postgres:// URL."
      export DATABASE_URL="$REPLY"
    fi
  fi
  if [[ -n "${VALKEY_URL:-}" ]]; then
    RD_CHOICE=url
  else
    opts=()
    [[ "$MODE" == docker ]] && opts+=(docker "Own Valkey 8 container")
    [[ "$RD_STATE" == running ]] && ((RD_AUTH == 0)) && opts+=(host "Valkey/Redis ${RD_VERSION} on this server - own database number")
    [[ "$MODE" == native && "$RD_STATE" == none ]] && opts+=(install "Install Valkey on this server")
    opts+=(url "Another Valkey or Redis - I give a VALKEY_URL")
    def="${opts[0]}"
    if [[ -n "$RD_MODE" ]]; then REPLY="$RD_MODE"; else choose "Valkey" "Where does the job queue run?" "$def" "${opts[@]}"; fi
    RD_CHOICE="$REPLY"
    if [[ "$RD_CHOICE" == url ]]; then
      ((YES)) && die "Set VALKEY_URL to use another Valkey."
      if ((TUI)); then tui_input "VALKEY_URL" "redis://:password@host:6379/0  (rediss:// for TLS)" ""; else ask "VALKEY_URL: " ""; fi
      [[ "$REPLY" == redis://* || "$REPLY" == rediss://* ]] || die "That is not a redis:// URL."
      export VALKEY_URL="$REPLY"
    fi
  fi
  if [[ "$MODE" == native && ( "$PG_CHOICE" == docker || "$RD_CHOICE" == docker ) ]]; then
    die "--postgres docker and --valkey docker are for Docker mode. Native mode uses Postgres and Valkey on this server (or DATABASE_URL, VALKEY_URL)."
  fi
  if [[ "$MODE" == docker ]]; then
    PG_MODE="$PG_CHOICE"; RD_MODE="$RD_CHOICE"
    if [[ "$PG_MODE" == url ]] && is_local_host "$(url_host "$DATABASE_URL")"; then PG_MODE=host; fi
    if [[ "$RD_MODE" == url ]] && is_local_host "$(url_host "$VALKEY_URL")"; then RD_MODE=host; fi
  fi

  # 7. Extras.
  extras=()
  if ((MEM_MB < 3900 && SWAP_MB == 0)) && [[ -z "$DO_SWAP" ]]; then
    extras+=(swap "Add 3 GB swap (RAM is ${MEM_MB} MB; the build needs it)" on)
  fi
  if [[ -n "$(fw_name)" && "$PROXY" =~ ^(caddy|nginx)$ && -z "$DO_FIREWALL" ]]; then
    extras+=(firewall "Allow ports 80 and 443 in $(fw_name)" on)
  fi
  if [[ "$PROXY" == nginx && "$SCHEME" == https && -z "$DO_CERTBOT" ]]; then
    extras+=(certbot "Get a free HTTPS certificate with certbot" on)
  fi
  if ((${#extras[@]})); then
    choose_many "Extras" "Pick what the script also does." "${extras[@]}"
    [[ -n "$DO_SWAP" ]] || { chosen swap && DO_SWAP=1 || DO_SWAP=0; }
    [[ -n "$DO_FIREWALL" ]] || { chosen firewall && DO_FIREWALL=1 || DO_FIREWALL=0; }
    [[ -n "$DO_CERTBOT" ]] || { chosen certbot && DO_CERTBOT=1 || DO_CERTBOT=0; }
  fi

  # 8. Advanced: port, admins, signup, version, backups, updates.
  ((AUTO)) || ((YES)) || ! have_tty || more_settings
  AUTO=0
fi
DO_SWAP="${DO_SWAP:-1}"; DO_FIREWALL="${DO_FIREWALL:-1}"; DO_CERTBOT="${DO_CERTBOT:-1}"

# Options: the value given now, else the one kept in the state file, else the default.
stored() { [[ "$ACTION" == update ]] && state_get "$DIR" "$1" || true; }
STORED_BIND=$(stored BIND); STORED_BIND="${STORED_BIND:-127.0.0.1}"
BIND="${BIND_ARG:-$STORED_BIND}"
# The address the proxy on this server uses to reach the app.
up_host() { if [[ "$1" == 0.0.0.0 ]]; then echo 127.0.0.1; else echo "$1"; fi; }
UP_HOST=$(up_host "$BIND")
OLD_UP_HOST=$(up_host "$STORED_BIND")
# An update that changes a port or the address: "old new" pairs, for the proxy site.
MOVES=()
moved_upstream() { [[ "$1" == "$2" ]] || MOVES+=("$1 $2"); }
STORED_VERSION=$(stored VERSION)
VERSION="${VERSION_ARG:-$STORED_VERSION}"
[[ "$VERSION" != latest ]] || VERSION=""
# For the plan: the release on this server now, and the newest release.
CUR_VERSION=""
[[ "$ACTION" != update || ! -f "$DIR/package.json" ]] \
  || CUR_VERSION=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' "$DIR/package.json" | head -1)
newest_release() {
  local tags=""
  if command -v git >/dev/null; then
    tags=$(GIT_TERMINAL_PROMPT=0 git -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=10 ls-remote --tags --refs -- "$ZERODOT_REPO" 'v*' 2>/dev/null | sed 's#.*refs/tags/v##' || true)
  fi
  if [[ -z "$tags" ]] && command -v curl >/dev/null && [[ "$ZERODOT_REPO" == https://github.com/* ]]; then
    local slug="${ZERODOT_REPO#https://github.com/}"; slug="${slug%.git}"
    tags=$(curl -fsSL --max-time 8 "https://api.github.com/repos/${slug}/releases/latest" 2>/dev/null \
      | sed -n 's/.*"tag_name": *"v\{0,1\}\([^"]*\)".*/\1/p' || true)
  fi
  printf '%s\n' "$tags" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -t. -k1,1n -k2,2n -k3,3n | tail -1 || true
}
NEWEST_VERSION=""
[[ -n "$VERSION" || -n "$ZERODOT_BRANCH" ]] || NEWEST_VERSION=$(newest_release)
# The release tag to check out. "latest" is the newest release, as the image tag latest is.
# Empty: follow the branch (ZERODOT_BRANCH, or the newest release is unknown).
CODE_VERSION="${VERSION:-$NEWEST_VERSION}"
version_text() {
  local to
  if [[ -n "$VERSION" ]]; then to="$VERSION"
  elif [[ -n "$ZERODOT_BRANCH" ]]; then to="branch $ZERODOT_BRANCH"
  elif [[ -n "$NEWEST_VERSION" ]]; then to="latest ($NEWEST_VERSION)"
  else to="latest (newest release unknown, follows the main branch)"; fi
  if [[ -z "$CUR_VERSION" ]]; then echo "$to"
  elif [[ "$to" == "$CUR_VERSION" || "$NEWEST_VERSION" == "$CUR_VERSION" ]]; then echo "$to, already installed"
  else echo "$CUR_VERSION to $to"; fi
}
STORED_DATA_DIR=$(stored DATA_DIR)
DATA_DIR="${DATA_DIR_ARG:-$STORED_DATA_DIR}"
if [[ "$ACTION" == update && -n "$DATA_DIR_ARG" && "$DATA_DIR_ARG" != "$STORED_DATA_DIR" ]]; then
  die "--data-dir is for a new install. The script does not move data. Move it by hand: see https://zerodot.io/docs/backup-and-move"
fi
if [[ -n "$DATA_DIR" && "$MODE" == native ]] && [[ "$DATA_DIR" == /home/* || "$DATA_DIR" == /root/* || "$DATA_DIR" == /run/user/* ]]; then
  die "--data-dir $DATA_DIR: the services cannot see /home, /root or /run/user (systemd ProtectHome). Use a folder such as /srv/${NAME} or /mnt/data/${NAME}."
fi
BACKUP="${BACKUP_ARG:-$(stored BACKUP)}"; BACKUP="${BACKUP:-off}"
BACKUP_DIR="${BACKUP_DIR_ARG:-$(stored BACKUP_DIR)}"
if [[ -z "$BACKUP_DIR" ]]; then
  if ((IS_MAC)); then BACKUP_DIR="$HOME/${NAME}-backups"; else BACKUP_DIR="/var/backups/${NAME}"; fi
fi
BACKUP_KEEP="${BACKUP_KEEP_ARG:-$(stored BACKUP_KEEP)}"; BACKUP_KEEP="${BACKUP_KEEP:-14}"
AUTO_UPDATE="${AUTO_UPDATE_ARG:-$(stored AUTO_UPDATE)}"; AUTO_UPDATE="${AUTO_UPDATE:-off}"
if [[ "$MODE" == native ]]; then
  for v in WORKER_REPLICAS SANDBOX_REPLICAS; do
    [[ -z "$(env_value "$v")" ]] || die "--workers and --sandboxes are for Docker mode. Native mode: use --concurrency."
  done
else
  [[ -z "$API_PORT_ARG$WORKER_PORT_ARG$SANDBOX_PORT_ARG" ]] || die "--api-port, --worker-port and --sandbox-port are for native mode. Docker mode has one port: --port."
fi
# Admin emails must look like emails.
for e in $(env_value ZERODOT_ADMIN_EMAILS | tr ',' ' '); do
  [[ "$e" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$ ]] || die "'$e' is not an email address (--admin-email)."
done
# Signup off on a new server, and nobody may sign up: nobody can ever sign in.
if [[ "$ACTION" == new && "$(env_value ZERODOT_SIGNUP_DISABLED)" == true && -z "$(env_value ZERODOT_ADMIN_EMAILS)" ]]; then
  die "--disable-signup on a new install needs --admin-email you@example.com. Else nobody can make the first account."
fi
# The ports must be free. A port that this install has now is fine.
CUR_PORTS=""
if [[ "$ACTION" == update ]] || ((REINSTALL)); then
  old="${OLD_DIR:-$DIR}"
  CUR_PORTS=" $(override_port "$old/docker-compose.override.yml") $(state_get "$old" PORT) $(state_get "$old" WEB_PORT) $(state_get "$old" API_PORT) $(state_get "$old" WORKER_PORT) $(state_get "$old" SANDBOX_PORT) "
fi
for p in $PORT_ARG $API_PORT_ARG $WORKER_PORT_ARG $SANDBOX_PORT_ARG; do
  [[ "$CUR_PORTS" == *" $p "* ]] && continue
  if [[ " $RESERVED " == *" $p "* ]]; then die "Port $p belongs to another Zerodot install on this server."; fi
  if port_in_use "$p"; then die "Port $p is in use$( [[ -n $(listener "$p") ]] && echo " by $(listener "$p")"). Give another port."; fi
done
[[ "$(printf '%s\n' $PORT_ARG $API_PORT_ARG $WORKER_PORT_ARG $SANDBOX_PORT_ARG | sort | uniq -d)" == "" ]] || die "Give each service its own port."
if [[ "$BIND" != 127.0.0.1 ]] && [[ "$PROXY" == none ]]; then
  tip "The app port is open on $BIND. It is plain HTTP: sign-in needs HTTPS except on localhost. Put a proxy with HTTPS in front for the internet."
fi
if [[ "$(env_value ZERODOT_ENABLE_EXECUTE_COMMAND)" == true ]]; then
  note "Execute Command is on: every user who can edit a workflow can run shell commands$([[ $MODE == docker ]] && echo " in the worker container" || echo " on this server as user ${NAME}")."
fi
[[ "$PROXY" =~ ^(caddy|nginx|cloudflared|none)$ ]] || die "Unknown proxy '$PROXY'."
# Caddy and nginx need ports 80 and 443 for themselves.
if [[ "$PROXY" == caddy || "$PROXY" == nginx ]] && [[ -n "$PORT_OWNER" && "$PORT_OWNER" != "$PROXY" ]]; then
  die "Ports 80/443 are used by $PORT_OWNER, so $PROXY cannot use them. Use --proxy $([[ $PORT_OWNER == caddy || $PORT_OWNER == nginx ]] && echo "$PORT_OWNER" || echo none), or --proxy cloudflared."
fi
# Ask for the tunnel token now, before anything changes.
if [[ "$PROXY" == cloudflared ]] && ! unit_exists cloudflared.service; then
  if [[ -z "$TUNNEL_TOKEN" && -f "$DIR/.env" ]]; then
    TUNNEL_TOKEN=$(grep -m1 '^ZERODOT_TUNNEL_TOKEN=' "$DIR/.env" | cut -d= -f2- || true)
  fi
  ask_tunnel_token
fi
if [[ "$MODE" == docker ]]; then
  PG_MODE="${PG_MODE:-docker}"; RD_MODE="${RD_MODE:-docker}"
  if [[ "$PG_MODE" == host && -z "${DATABASE_URL:-}" ]]; then
    ((PG_VERNUM >= 130000)) || die "--postgres host needs Postgres 13+ running on this server, with access as the postgres user. Or set DATABASE_URL."
  fi
  if [[ "$RD_MODE" == host && -z "${VALKEY_URL:-}" ]]; then
    [[ "$RD_STATE" == running ]] || die "--valkey host needs Valkey or Redis running on this server on port 6379. Or set VALKEY_URL."
    ((RD_AUTH == 0)) || die "Valkey/Redis on this server needs a password. Set VALKEY_URL=redis://:PASSWORD@127.0.0.1:6379/N and run again."
  fi
fi
[[ "$MODE" == docker || "$MODE" == native ]] || die "Unknown mode '$MODE'."
if [[ "$MODE" == docker && "$DOCKER_OK" == 0 && "$HAS_DOCKER" == 1 ]]; then
  die "Docker is installed but not usable (see above). Fix it, or use --native."
fi
DBNAME="${NAME//-/_}"

# Checks that stop the run before it changes anything.
OLD_ENV="$DIR/.env"; ((REINSTALL == 0)) || OLD_ENV=/dev/null
if [[ "$MODE" == native && -z "${DATABASE_URL:-}" ]] && ! grep -qs '^DATABASE_URL=postgres.*@127\.0\.0\.1:' "$OLD_ENV"; then
  case "$PG_STATE" in
    installed) die "Postgres is installed but stopped. The script does not start it. Start it (systemctl start postgresql), or set DATABASE_URL." ;;
    client) die "Only the Postgres client is installed. Install the Postgres server, or set DATABASE_URL." ;;
    running) ((PG_VERNUM > 0)) || die "Postgres runs, but the script cannot log in as the postgres user. Set DATABASE_URL to a database for Zerodot." ;;
  esac
fi
if [[ "$MODE" == native && -z "${VALKEY_URL:-}" ]] && ! grep -qs '^VALKEY_URL=.*127\.0\.0\.1' "$OLD_ENV"; then
  [[ "$RD_STATE" != installed ]] || die "Valkey/Redis is installed but stopped. The script does not start or change it. Start it, or set VALKEY_URL."
  ((RD_AUTH == 0)) || die "Valkey/Redis on this server needs a password. Set VALKEY_URL=redis://:PASSWORD@127.0.0.1:6379/N and run again."
fi
if [[ "$ACTION" == update && ! -f "$DIR/.env" ]]; then
  die "$DIR has no .env. A new .env has new secret keys, and the saved credentials cannot be opened with them. Put back the old .env (from a backup), then run again."
fi
# A Docker volume from an old install with the same folder name holds a database with another password.
if [[ "$MODE" == docker && ! -f "$DIR/.env" ]] && command -v docker >/dev/null; then
  project=$(compose_project "$DIR")
  other=$(project_owner "$DIR")
  [[ -z "$other" ]] || die "The Docker project '${project}' already belongs to ${other}. This install would share its containers and data.
Pick another name: --name ${project}-2 (or another --dir)."
fi
if [[ "$MODE" == docker && "$PG_MODE" == docker && ! -f "$DIR/.env" ]] && command -v docker >/dev/null; then
  if [[ -n "$(docker volume ls -q --filter "name=^${project}_postgres-data\$" 2>/dev/null)" ]]; then
    die "Docker volume ${project}_postgres-data is from an old install. It holds a database with the old password.
Put the old .env in $DIR to use it, or pick another --name. To delete the old data: docker volume rm ${project}_postgres-data"
  fi
fi

# ---------------------------------------------------------------------------
# Step 3: plan
# ---------------------------------------------------------------------------
plan_text() {
  [[ "$SETUP" != recommended ]] || echo "  Setup:    recommended. For more choices: answer No, run again, pick 'Set up again', then Advanced"
  ((REINSTALL == 0)) || echo "  Removes:  ${OLD_NAME} in ${OLD_DIR} ($OLD_MODE), with its data"
  printf '  Action:   %s\n  Mode:     %s\n  Name:     %s\n  Folder:   %s\n  Address:  %s://%s\n' "$ACTION" "$MODE" "$NAME" "$DIR" "$SCHEME" "$DOMAIN"
  if [[ "$MODE" == native ]]; then
    case "$PG_STATE" in
      external) echo "  Database: your DATABASE_URL" ;;
      running) echo "  Database: share Postgres on this server (new database '$DBNAME' and user)" ;;
      *) echo "  Database: install Postgres (package)" ;;
    esac
    case "$RD_STATE" in
      external) echo "  Queue:    your VALKEY_URL" ;;
      running) echo "  Queue:    share Valkey/Redis on this server (own database number)" ;;
      *) echo "  Queue:    install Valkey or Redis (package)" ;;
    esac
  else
    case "$PG_MODE" in
      host) echo "  Database: Postgres on this server, reached from the containers" ;;
      url) echo "  Database: your DATABASE_URL" ;;
      *) echo "  Database: Postgres 17 container" ;;
    esac
    case "$RD_MODE" in
      host) echo "  Queue:    Valkey/Redis on this server, reached from the containers" ;;
      url) echo "  Queue:    your VALKEY_URL" ;;
      *) echo "  Queue:    Valkey 8 container" ;;
    esac
  fi
  case "$PROXY" in
    caddy) echo "  Proxy:    Caddy (installed if missing)" ;;
    nginx) echo "  Proxy:    nginx site (nginx installed if missing), HTTPS from certbot" ;;
    cloudflared) echo "  Proxy:    Cloudflare Tunnel (no ports opened)" ;;
    none) echo "  Proxy:    not changed (you add the rule)" ;;
  esac
  local port="${PORT_ARG:-}"
  [[ -n "$port" ]] || { [[ "$ACTION" == update ]] && port=$(state_get "$DIR" "$([[ $MODE == docker ]] && echo PORT || echo WEB_PORT)"); }
  echo "  Port:     ${BIND}:${port:-first free from 3000}"
  echo "  Version:  $(version_text)"
  [[ -z "$DATA_DIR" ]] || echo "  Data:     $DATA_DIR"
  [[ "$BACKUP" == off ]] || echo "  Backups:  $BACKUP to $BACKUP_DIR (keep $BACKUP_KEEP)"
  [[ "$AUTO_UPDATE" == off ]] || echo "  Updates:  $AUTO_UPDATE"
  if ((${#ENV_SETS[@]})); then
    local kv
    echo "  Settings:"
    for kv in "${ENV_SETS[@]}"; do
      case "${kv%%=*}" in
        *SECRET* | *PASSWORD* | *TOKEN* | *KEY*) echo "    ${kv%%=*}=(hidden)" ;;
        *) echo "    $kv" ;;
      esac
    done
  fi
}
PLAN=$(plan_text)
say "Plan"
echo "$PLAN"
if ((TUI)); then
  if [[ "$MODE" == docker ]]; then
    tui_yesno "Ready to start?" "$PLAN

Docker mode pulls the images. The first start takes a few minutes." || tui_cancel
  else
    tui_yesno "Ready to start?" "$PLAN

The first build takes about 10 minutes." || tui_cancel
  fi
else
  confirm "Continue?" || { echo "Stopped. Nothing was changed."; exit 0; }
fi
# Set up again: remove the old install now. A new mode uses the old mode for the removal.
if ((REINSTALL)); then
  NEW_MODE="$MODE"; NEW_NAME="$NAME"; NEW_DIR="$DIR"
  MODE="$OLD_MODE"; NAME="$OLD_NAME"; DIR="$OLD_DIR"
  uninstall_instance "$OLD_PROXY"
  MODE="$NEW_MODE"; NAME="$NEW_NAME"; DIR="$NEW_DIR"
fi

# ---------------------------------------------------------------------------
# Step 4: base packages, swap, firewall
# ---------------------------------------------------------------------------
if ((IS_MAC == 0)); then
  say "Installing base packages"
  # shellcheck disable=SC2046
  pkg_install $(pkgs_base)
fi

# Swap. Never touches a swap file that exists. Failure is only a warning.
add_swap() {
  local fs
  if [[ "$VIRT" == lxc || "$VIRT" == openvz ]]; then note "No swap: a container ($VIRT) cannot add swap."; return; fi
  if [[ -e /swapfile ]]; then note "/swapfile exists but is off. Not touched. Turn it on with: swapon /swapfile"; return; fi
  say "Adding 3 GB swap (RAM is ${MEM_MB} MB)"
  fs=$(stat -f -c %T / 2>/dev/null || true)
  if [[ "$fs" == btrfs ]]; then
    # A swap file on btrfs must not use copy-on-write.
    btrfs filesystem mkswapfile --size 3g /swapfile >/dev/null 2>&1 || { rm -f /swapfile; note "Cannot make a swap file on btrfs. Add swap by hand."; return; }
  else
    fallocate -l 3G /swapfile 2>/dev/null || dd if=/dev/zero of=/swapfile bs=1M count=3072 status=none
    chmod 600 /swapfile
    mkswap /swapfile >/dev/null
  fi
  if swapon /swapfile 2>/dev/null; then
    grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
    changed "Added 3 GB swap in /swapfile (and in /etc/fstab)"
  else
    rm -f /swapfile
    note "swapon failed. No swap added."
  fi
}
if ((MEM_MB < 3900 && SWAP_MB == 0 && DO_SWAP)); then add_swap; fi

if [[ "$PROXY" == caddy || "$PROXY" == nginx ]] && ((DO_FIREWALL)); then fw_open_web; fi

# ---------------------------------------------------------------------------
# Step 5: code
# ---------------------------------------------------------------------------
say "Getting the code in $DIR"
if [[ -d "$DIR/.git" ]]; then
  # Local changes stay. A pull that cannot fast-forward stops here and changes nothing.
  # Native mode: the service user owns the folder. Git as root then stops ("dubious ownership"),
  # so run it as the owner.
  as_owner=()
  if ((IS_MAC == 0)); then
    owner=$(stat -c %U "$DIR")
    [[ "$owner" == root ]] || as_owner=(runuser -u "$owner" -- env HOME="$DIR")
  fi
  git_dir() { GIT_TERMINAL_PROMPT=0 "${as_owner[@]}" git -C "$DIR" -c advice.detachedHead=false "$@"; }
  if [[ -n "$CODE_VERSION" ]]; then
    # A release: the tag vX.Y.Z (fixed, or the newest for "latest").
    git_dir fetch --quiet --tags --force origin || die "git fetch failed in $DIR. Check the network."
    cur_branch=$(git_dir symbolic-ref -q --short HEAD 2>/dev/null || true)
    if [[ -n "$cur_branch" ]] && git_dir merge-base --is-ancestor "v${CODE_VERSION}" HEAD 2>/dev/null \
      && [[ "$(git_dir rev-parse HEAD)" != "$(git_dir rev-parse "v${CODE_VERSION}^{commit}" 2>/dev/null)" ]]; then
      note "The code moves from the branch ${cur_branch} (ahead of v${CODE_VERSION}) to release v${CODE_VERSION}."
    fi
    git_dir checkout --quiet "v${CODE_VERSION}" \
      || die "Cannot switch $DIR to release v${CODE_VERSION}. No such release, or local changes. Releases: https://github.com/zerodot-io/zerodot/releases"
    ok "Code at release v${CODE_VERSION}"
  elif [[ -n "$ZERODOT_BRANCH" ]]; then
    # ZERODOT_BRANCH: follow the branch.
    if ! git_dir symbolic-ref -q HEAD >/dev/null; then
      git_dir checkout --quiet "$ZERODOT_BRANCH" || die "Cannot switch $DIR to the branch ${ZERODOT_BRANCH}. See: git -C $DIR status"
    fi
    git_dir pull --ff-only \
      || die "git pull failed in $DIR. Local changes or another branch? See: git -C $DIR status"
  elif ! git_dir symbolic-ref -q HEAD >/dev/null; then
    # The newest release is unknown and HEAD is on a release: keep it.
    note "Newest release unknown. The code stays at $(git_dir describe --tags --always 2>/dev/null || echo HEAD)."
  else
    git_dir pull --ff-only \
      || die "git pull failed in $DIR. Local changes or another branch? See: git -C $DIR status"
  fi
else
  mkdir -p "$(dirname "$DIR")"
  ref="${ZERODOT_BRANCH:-${CODE_VERSION:+v$CODE_VERSION}}"
  GIT_TERMINAL_PROMPT=0 git -c advice.detachedHead=false clone ${ref:+-b "$ref"} "$ZERODOT_REPO" "$DIR" \
    || die "Clone failed. Check the network, ZERODOT_REPO ($ZERODOT_REPO)$([[ -n $CODE_VERSION ]] && echo " and that release v$CODE_VERSION exists")."
  changed "Cloned the code to $DIR${CODE_VERSION:+ (release v$CODE_VERSION)}"
fi
cd "$DIR"

# What the repository needs.
PM_VER=$(sed -n 's/.*"packageManager": *"pnpm@\([^"]*\)".*/\1/p' package.json | head -1)
NODE_REQ=$(sed -n 's/.*"node": *">=\([0-9]*\).*/\1/p' package.json | head -1)
NODE_REQ="${NODE_REQ:-22}"
[[ -n "$PM_VER" ]] || die "Cannot read the pnpm version from package.json."

# ---------------------------------------------------------------------------
# Step 6: settings (.env). Existing values stay.
# ---------------------------------------------------------------------------
say "Writing .env"
FRESH_ENV=false
[[ -f .env ]] || { cp .env.example .env; FRESH_ENV=true; }
chmod 600 .env

set_env() {
  local key="$1" value="$2" escaped
  escaped=$(printf '%s' "$value" | sed 's/[|&\\]/\\&/g')
  # BSD sed (macOS) needs an argument after -i.
  if grep -q "^${key}=" .env; then sed -i.zerodot-tmp "s|^${key}=.*|${key}=${escaped}|" .env && rm -f .env.zerodot-tmp; else echo "${key}=${value}" >> .env; fi
}
set_env_once() { grep -Eq "^${1}=.+" .env || set_env "$1" "$2"; }
get_env() { grep -m1 "^${1}=" .env | cut -d= -f2- || true; }

# Write the state early, so a run that stops half-way can continue as the same mode.
write_state() {
  {
    printf 'MODE=%s\nNAME=%s\nDOMAIN=%s\nSCHEME=%s\nPROXY=%s\n' "$MODE" "$NAME" "$DOMAIN" "$SCHEME" "$PROXY"
    printf 'BIND=%s\nVERSION=%s\nDATA_DIR=%s\n' "$BIND" "$VERSION" "$DATA_DIR"
    printf 'BACKUP=%s\nBACKUP_DIR=%s\nBACKUP_KEEP=%s\nAUTO_UPDATE=%s\n' "$BACKUP" "$BACKUP_DIR" "$BACKUP_KEEP" "$AUTO_UPDATE"
    [[ "$MODE" == docker ]] && printf 'PG_MODE=%s\nRD_MODE=%s\n' "$PG_MODE" "$RD_MODE"
    printf 'DONE=%s\n' "$DONE"
    for k in "$@"; do printf '%s=%s\n' "$k" "${!k}"; done
    # Keep the ports of an earlier run that this call does not give. Else a run that stops
    # half way loses them, and the next run picks new ports that the proxy site does not know.
    local pk old
    for pk in PORT WEB_PORT API_PORT WORKER_PORT SANDBOX_PORT; do
      [[ " $* " == *" $pk "* ]] && continue
      old=$(grep -m1 "^${pk}=" "$STATE_FILE" 2>/dev/null | cut -d= -f2- || true)
      [[ "$old" =~ ^[0-9]+$ ]] && printf '%s=%s\n' "$pk" "$old"
    done
  } > "$STATE_FILE.new"
  mv -f "$STATE_FILE.new" "$STATE_FILE"
  # Linux: a copy that only root can change. Native mode gives the folder to the service user,
  # so the zerodot command trusts this copy, not the one in the folder.
  if ((IS_MAC == 0)); then
    mkdir -p /etc/zerodot && chmod 755 /etc/zerodot
    rm -f "/etc/zerodot/${NAME}.state"
    { cat "$STATE_FILE"; printf 'DIR=%s\n' "$(readlink -f "$DIR")"; } > "/etc/zerodot/${NAME}.state"
    chmod 644 "/etc/zerodot/${NAME}.state"
  fi
}
write_state

set_env_once ZERODOT_SECRET_KEY "$(openssl rand -base64 32)"
set_env_once BETTER_AUTH_SECRET "$(openssl rand -base64 32)"
set_env ZERODOT_BASE_URL "${SCHEME}://${DOMAIN}"
# Native mode with the port open and no proxy: clients connect directly and could fake X-Forwarded-For.
if [[ "$MODE" == native && "$BIND" != 127.0.0.1 && "$PROXY" == none ]]; then
  set_env ZERODOT_TRUST_PROXY "false"
else
  set_env ZERODOT_TRUST_PROXY "true"
fi
# The image tag follows the release. "latest" again when the install leaves a fixed release.
if [[ -n "$VERSION" ]]; then set_env ZERODOT_VERSION "$VERSION"
elif [[ -n "$STORED_VERSION" ]]; then set_env ZERODOT_VERSION latest; fi
# The options. The last value for a key wins.
for kv in "${ENV_SETS[@]}"; do set_env "${kv%%=*}" "${kv#*=}"; done
((${#ENV_SETS[@]} == 0)) || ok "Wrote ${#ENV_SETS[@]} setting(s) from the options to .env"

# ===========================================================================
# DOCKER MODE
# ===========================================================================
# Remove old Zerodot images. The images that a container uses stay (docker rmi refuses those).
prune_old_images() {
  local repo ids
  repo="${ZERODOT_IMAGE:-$(get_env ZERODOT_IMAGE 2>/dev/null || true)}"
  repo="${repo:-ghcr.io/zerodot-io/zerodot}"
  ids=$(docker images "$repo" --format '{{.ID}}' 2>/dev/null | sort -u || true)
  [[ -n "$ids" ]] || return 0
  # shellcheck disable=SC2086
  docker rmi $ids >/dev/null 2>&1 || true
  # Images without a tag, left by the pull.
  docker image prune -f >/dev/null 2>&1 || true
}

docker_mode() {
  set_env_once ZERODOT_BLOB_DIR "/blobs"
  # Passwords for the database and Valkey, so that nothing else in the network can use them.
  set_env_once ZERODOT_VALKEY_PASSWORD "$(openssl rand -hex 24)"
  if [[ "$FRESH_ENV" == true ]]; then
    set_env_once ZERODOT_DB_PASSWORD "$(openssl rand -hex 24)"
  else
    # An install from before this setting. Its database was made with the password "zerodot".
    set_env_once ZERODOT_DB_PASSWORD "zerodot"
    [[ "$(get_env ZERODOT_DB_PASSWORD)" != zerodot || "$PG_MODE" != docker ]] \
      || tip "The database password is still 'zerodot'. docs/deploy-vps.md tells how to change it."
  fi

  command -v docker >/dev/null || install_docker
  docker compose version >/dev/null 2>&1 || die "Docker Compose v2 is missing. Update Docker and run again."
  ver_ge "$(docker compose version --short | sed 's/^v//')" 2.24.0 || die "Docker Compose is older than 2.24. Update Docker."

  # The proxy listens on localhost only, so only the proxy on this server can reach it.
  local cur
  cur=$(override_port docker-compose.override.yml)
  if [[ -n "$PORT_ARG" ]]; then
    PORT="$PORT_ARG"
  elif [[ -n "$cur" ]]; then
    PORT="$cur"
  else
    free_port 3000
    PORT="$FREE_PORT"
  fi
  # --local: the address is the port on this computer.
  if [[ "$DOMAIN" == localhost || "$DOMAIN" == localhost:* ]] && [[ "$DOMAIN" != "localhost:${PORT}" ]]; then
    DOMAIN="localhost:${PORT}"
    set_env ZERODOT_BASE_URL "http://${DOMAIN}"
    write_state
  fi

  [[ -z "$cur" ]] || moved_upstream "${OLD_UP_HOST}:${cur}" "${UP_HOST}:${PORT}"
  docker_data_dir
  docker_files_dir

  docker_database
  docker_queue
  docker_tunnel_token
  write_override

  # Use the images from GHCR. Build on the server only if the pull fails.
  if ! docker compose pull --quiet; then
    say "Pull failed. Building on this server (the first build takes about 10 minutes)"
    docker compose build
  fi
  # Make the network first: the database on this server must allow its address.
  docker compose up --no-start >/dev/null
  # After a move to Postgres or Valkey outside Docker, compose no longer manages the old
  # container. Stop it. Its data volume stays.
  local svc ids project
  project=$(docker compose config 2>/dev/null | sed -n 's/^name: //p' | head -1)
  for svc in postgres valkey; do
    [[ "$svc" == postgres && "$PG_MODE" == docker ]] && continue
    [[ "$svc" == valkey && "$RD_MODE" == docker ]] && continue
    ids=$(docker ps -q --filter "label=com.docker.compose.project=${project}" --filter "label=com.docker.compose.service=${svc}")
    if [[ -n "$ids" ]]; then
      docker stop $ids >/dev/null
      changed "Stopped the old $svc container of ${project} (its volume ${project}_${svc}-data stays)"
    fi
  done
  # Docker Desktop and OrbStack send host.docker.internal to the localhost of the Mac,
  # so Postgres and Valkey need no change there.
  if [[ "$PG_MODE" == host || "$RD_MODE" == host ]] && ((IS_MAC == 0)); then
    docker_host_access
  fi
  [[ "$PG_MODE" == docker ]] || docker_reach postgres "$(get_env DATABASE_URL)" 5432
  [[ "$RD_MODE" == docker ]] || docker_reach valkey "$(get_env VALKEY_URL)" 6379

  say "Starting"
  docker compose up -d --remove-orphans

  UPSTREAM_PORT="$PORT"
  wait_http "http://${UP_HOST}:${PORT}/" || {
    docker compose ps
    docker compose logs --tail 20 api || true
    die "The app did not start. See: cd $DIR && docker compose logs"
  }
  # The new version answers. Only now remove the old images.
  prune_old_images
  CADDY_KIND="single"
  write_state PORT
}

install_docker() {
  ((IS_MAC == 0)) || die "Docker is not installed. Install Docker Desktop or OrbStack, start it, and run again."
  say "Installing Docker"
  case "$OS_FAMILY" in
    debian) curl -fsSL https://get.docker.com | sh ;;
    fedora | rhel)
      # The Docker CE repository. get.docker.com does not know Rocky and Alma.
      add_repo_file "https://download.docker.com/linux/$([[ $OS_FAMILY == fedora ]] && echo fedora || echo centos)/docker-ce.repo" /etc/yum.repos.d/docker-ce.repo
      pkg_install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin \
        || die "Docker CE did not install. If dnf names a conflict with podman, buildah or runc: the script does not remove them. Remove them yourself, or use --native."
      ;;
    arch) pkg_install docker docker-compose docker-buildx ;;
  esac
  command -v docker >/dev/null || die "Docker did not install."
  changed "Installed Docker"
  svc_start docker
}

# Postgres for the containers: own container, the one on this server, or DATABASE_URL.
docker_database() {
  local url
  case "$PG_MODE" in
    docker) return ;;
    url)
      [[ -z "${DATABASE_URL:-}" ]] || set_env DATABASE_URL "$DATABASE_URL"
      ;;
    host)
      if [[ -n "${DATABASE_URL:-}" ]]; then
        set_env DATABASE_URL "$(to_docker_host "$DATABASE_URL")"
      elif [[ "$(get_env DATABASE_URL)" != *"@host.docker.internal:"* ]]; then
        # A new database and user, as in native mode.
        pg_create_db
        set_env DATABASE_URL "postgres://${DBNAME}:${PG_NEW_PASS}@host.docker.internal:${PG_PORT}/${DBNAME}"
      else
        ok "Database: keeping DATABASE_URL from .env"
      fi
      ;;
  esac
  url=$(get_env DATABASE_URL)
  [[ -n "$url" ]] || die "No DATABASE_URL. Set it and run again."
  case "$url" in *sslmode=* | *@host.docker.internal:*) ;; *) note "DATABASE_URL has no sslmode. A hosted database (RDS, Neon, Supabase) usually needs ?sslmode=require." ;; esac
  [[ "$url" != *":6543/"* ]] || note "Port 6543 is a pooler in transaction mode on Supabase. Use the session pooler or a direct connection."
}

# Valkey for the containers: own container, the one on this server, or VALKEY_URL.
docker_queue() {
  case "$RD_MODE" in
    docker) return ;;
    url) [[ -z "${VALKEY_URL:-}" ]] || set_env VALKEY_URL "$VALKEY_URL" ;;
    host)
      if [[ -n "${VALKEY_URL:-}" ]]; then
        set_env VALKEY_URL "$(to_docker_host "$VALKEY_URL")"
      elif [[ "$(get_env VALKEY_URL)" != *"host.docker.internal"* ]]; then
        redis_free_db
        set_env VALKEY_URL "redis://host.docker.internal:6379/${RD_DB}"
      else
        ok "Queue: keeping VALKEY_URL from .env"
      fi
      ;;
  esac
  [[ -n "$(get_env VALKEY_URL)" ]] || die "No VALKEY_URL. Set it and run again."
  [[ "$(get_env VALKEY_URL)" != *upstash* ]] || note "Upstash is a poor fit for the job queue (request limits, eviction). A normal Valkey or Redis is better."
}

# A tunnel container runs when the tunnel is new. A cloudflared on this server gets a hostname instead.
TUNNEL_IN_DOCKER=0
docker_tunnel_token() {
  [[ "$PROXY" == cloudflared ]] || return 0
  if unit_exists cloudflared.service; then return 0; fi
  TUNNEL_IN_DOCKER=1
  [[ -n "$TUNNEL_TOKEN" ]] || TUNNEL_TOKEN=$(get_env ZERODOT_TUNNEL_TOKEN)
  ask_tunnel_token
  set_env ZERODOT_TUNNEL_TOKEN "$TUNNEL_TOKEN"
}

# docker-compose.override.yml, made from the choices. Run the script again to change it.
write_override() {
  local s ext=0 hosts=0 mount=""
  [[ "$PG_MODE" == docker && "$RD_MODE" == docker ]] || ext=1
  [[ "$PG_MODE" == host || "$RD_MODE" == host ]] && hosts=1
  selinux_enforcing && mount=",z"
  {
    echo "# Written by scripts/install.sh. Run the script again to change it. Edits here are lost."
    echo "services:"
    echo "  proxy:"
    echo "    ports: !override"
    echo "      - \"${BIND}:${PORT}:3000\""
    # SELinux: label the mounted Caddyfile so the container can read it.
    if selinux_enforcing; then
      echo "    volumes: !override"
      echo "      - ./Caddyfile:/etc/caddy/Caddyfile:ro,z"
    fi
    # A profile that nobody turns on: the container is not made.
    [[ "$PG_MODE" == docker ]] || printf '  postgres:\n    profiles: [bundled-postgres]\n'
    [[ "$RD_MODE" == docker ]] || printf '  valkey:\n    profiles: [bundled-valkey]\n'
    if ((ext)) || [[ -n "$DATA_DIR" ]]; then
      for s in web api worker; do
        echo "  $s:"
        if [[ -n "$DATA_DIR" ]]; then
          echo "    volumes: !override"
          echo "      - \"${DATA_DIR}/blobs:/blobs${mount}\""
          echo "      - \"${DATA_DIR}/nodes:/nodes${mount}\""
        fi
        ((ext)) || continue
        ((hosts)) && echo '    extra_hosts: ["host.docker.internal:host-gateway"]'
        echo "    environment:"
        [[ "$PG_MODE" == docker ]] || echo '      DATABASE_URL: ${DATABASE_URL:?set DATABASE_URL}'
        [[ "$RD_MODE" == docker ]] || echo '      VALKEY_URL: ${VALKEY_URL:?set VALKEY_URL}'
        local deps=()
        [[ "$PG_MODE" == docker ]] && deps+=("      postgres: { condition: service_healthy }")
        [[ "$RD_MODE" == docker ]] && deps+=("      valkey: { condition: service_healthy }")
        [[ "$s" == worker ]] && deps+=("      sandbox: { condition: service_started }")
        if ((${#deps[@]})); then
          echo "    depends_on: !override"
          printf '%s\n' "${deps[@]}"
        else
          echo "    depends_on: !reset []"
        fi
      done
    fi
    if ((TUNNEL_IN_DOCKER)); then
      cat <<'CONF'
  cloudflared:
    image: cloudflare/cloudflared:latest
    command: [tunnel, --no-autoupdate, run]
    environment:
      TUNNEL_TOKEN: ${ZERODOT_TUNNEL_TOKEN:?set ZERODOT_TUNNEL_TOKEN}
    restart: unless-stopped
    depends_on: [proxy]
CONF
    fi
  } > docker-compose.override.yml
}

# --data-dir in Docker mode: folders on the host in place of the volumes. The app runs as
# the user node (uid 1000) in the image.
docker_data_dir() {
  [[ -n "$DATA_DIR" ]] || return 0
  local d
  for d in "$DATA_DIR/blobs" "$DATA_DIR/nodes"; do
    [[ -d "$d" ]] && continue
    mkdir -p "$d"
    ((IS_MAC)) || chown 1000:1000 "$d"
    changed "Made $d"
  done
}

# --files-dir in Docker mode: the worker sees the folder as /files. The app runs as uid 1000.
docker_files_dir() {
  [[ -n "$FILES_DIR_ARG" ]] || return 0
  [[ -d "$FILES_DIR_ARG" ]] || { mkdir -p "$FILES_DIR_ARG"; changed "Made $FILES_DIR_ARG"; }
  chmod 750 "$FILES_DIR_ARG"
  ((IS_MAC)) || chown 1000:1000 "$FILES_DIR_ARG"
  set_env ZERODOT_FILES_DIR /files
  set_env ZERODOT_FILES_HOST_DIR "$FILES_DIR_ARG"
}

# The address of the host as the containers see it (host-gateway): the docker0 bridge.
docker_gateway() {
  local gw=""
  [[ -f /etc/docker/daemon.json ]] && gw=$(grep -o '"host-gateway-ip"[^,}]*' /etc/docker/daemon.json | grep -oE '[0-9]+(\.[0-9]+){3}' || true)
  [[ -n "$gw" ]] || gw=$(ip -4 -o addr show docker0 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1)
  echo "${gw:-172.17.0.1}"
}

# The subnet of the default network of this compose project.
compose_subnet() {
  local project net
  project=$(docker compose config 2>/dev/null | sed -n 's/^name: //p' | head -1)
  net=$(docker network ls -q --filter "label=com.docker.compose.project=${project}" --filter "label=com.docker.compose.network=default" | head -1)
  [[ -n "$net" ]] || return 0
  docker network inspect -f '{{range .IPAM.Config}}{{.Subnet}} {{end}}' "$net" | tr ' ' '\n' | grep -m1 -E '^[0-9.]+/[0-9]+$' || true
}

# Postgres and Valkey on this server listen on localhost only, as a rule. The containers come
# from the Docker network, so the services must also listen on the bridge address and let that
# network in. Ask first: this changes services that other apps can use.
docker_host_access() {
  local gw subnet
  gw=$(docker_gateway)
  subnet=$(compose_subnet)
  [[ -n "$subnet" ]] || die "Cannot find the Docker network of this install. Run: docker compose up --no-start, then run the script again."
  say "Letting the containers ($subnet) reach this server ($gw)"
  [[ "$PG_MODE" == host ]] && pg_allow_docker "$gw" "$subnet"
  [[ "$RD_MODE" == host ]] && rd_allow_docker "$gw" "$subnet"
  return 0
}

# pg_hba_add LINE: put LINE before the first rule (the first match wins), with a copy of the file.
pg_hba_add() {
  local hba="$1" line="$2"
  grep -qxF "$line" "$hba" && return 0
  backup "$hba"
  awk -v add="# Added by Zerodot install.sh (${NAME})\n${line}" '!done && $0 !~ /^[[:space:]]*(#|$)/ { print add; done = 1 } { print } END { if (!done) print add }' "$BACKUP" > "$hba"
  changed "pg_hba.conf: added '$line'"
}

pg_allow_docker() {
  local gw="$1" subnet="$2" url listen hba enc method line user db port restart=0
  url=$(get_env DATABASE_URL)
  user=$(url_user "$url"); db=$(url_path "$url"); port=$(url_port "$url")
  user="${user:-all}"; db="${db:-all}"; port="${port:-5432}"
  detect_postgres
  ((PG_VERNUM > 0)) || die "Cannot log in to Postgres as the postgres user. Let ${subnet} reach Postgres by hand: listen_addresses, pg_hba.conf and the firewall."
  listen=$(pg_run -c 'show listen_addresses')
  hba=$(pg_run -c 'show hba_file')
  enc=$(pg_run -c 'show password_encryption')
  method=scram-sha-256; [[ "$enc" == md5 ]] && method=md5
  line="host ${db} ${user} ${subnet} ${method}"
  local todo=()
  if [[ "$listen" != "*" && ",${listen// /}," != *",${gw},"* ]]; then
    todo+=("listen_addresses: '${listen}' -> '${listen},${gw}'. Postgres RESTARTS: other apps lose their connections for some seconds.")
    restart=1
  fi
  grep -qxF "$line" "$hba" || todo+=("${hba}: add '${line}' (only this database and user, only the Docker network)")
  [[ -n "$(fw_name)" ]] && todo+=("$(fw_name): allow ${subnet} to ${gw} port ${port}")
  if ((${#todo[@]})); then
    ask_change "Change Postgres" "Postgres on this server must let the Zerodot containers in:
$(printf ' - %s\n' "${todo[@]}")
${gw} is the Docker bridge. It is not on the internet." \
      || die "Postgres not changed. Make these changes by hand and run again (or add --allow-host-changes):
$(printf ' - %s\n' "${todo[@]}")"
    if ((restart)); then
      pg_run -c "alter system set listen_addresses = '${listen},${gw}'"
      changed "Postgres: listen_addresses = '${listen},${gw}' (postgresql.auto.conf; undo: ALTER SYSTEM RESET listen_addresses)"
    fi
    pg_hba_add "$hba" "$line"
    [[ -z "$(fw_name)" ]] || fw_allow_from "$subnet" "$gw" "$port"
  fi
  # At boot, the bridge address exists only after Docker starts.
  after_docker postgresql@.service
  after_docker postgresql.service
  if ((restart)); then systemctl restart postgresql; sleep 3; else pg_run -c 'select pg_reload_conf()' >/dev/null; fi
  local max
  max=$(pg_run -c 'show max_connections' || echo 0)
  max="${max:-0}"
  ((max >= 150)) || note "Postgres max_connections is ${max}. One worker uses about 30, web and api 10 each. Other apps share it."
  ok "Postgres lets the containers in"
}

# rd_check_policy CLI...: the queue loses jobs if Valkey evicts keys. Other apps can need eviction.
rd_check_policy() {
  local policy maxmem
  policy=$("$@" config get maxmemory-policy 2>/dev/null | sed -n 2p | tr -d '\r')
  maxmem=$("$@" config get maxmemory 2>/dev/null | sed -n 2p | tr -d '\r')
  [[ "$policy" == noeviction || -z "$policy" ]] && return 0
  if [[ "${maxmem:-0}" == 0 ]]; then
    note "Valkey/Redis uses '$policy' but has no maxmemory, so it evicts nothing now. If someone sets maxmemory, jobs can vanish."
    return 0
  fi
  ask_change "Valkey eviction" "Valkey/Redis on this server evicts keys ('$policy', maxmemory ${maxmem}). The job queue loses jobs when it does.
The script can set 'maxmemory-policy noeviction'. Other apps that use it as a cache then get errors when memory is full." \
    || die "Valkey/Redis not changed. Use the Valkey container (--valkey docker), another Valkey (VALKEY_URL), or set 'maxmemory-policy noeviction' yourself."
  "$@" config set maxmemory-policy noeviction >/dev/null
  "$@" config rewrite >/dev/null 2>&1 || note "Could not save maxmemory-policy to the Valkey config file. Add it there, or it goes back at the next restart."
  changed "Valkey/Redis: maxmemory-policy '$policy' -> 'noeviction'"
}

rd_allow_docker() {
  local gw="$1" subnet="$2" cli=("${RD_CLI:-redis-cli}" -h 127.0.0.1) bind major url u pw
  detect_redis
  # The password and user from VALKEY_URL (URL-encoded).
  url=$(get_env VALKEY_URL); u=$(url_user "$url"); pw=$(url_pass "$url")
  [[ -z "$pw" ]] || cli+=(--no-auth-warning -a "$(printf '%b' "${pw//%/\\x}")")
  [[ -z "$u" ]] || cli+=(--user "$u")
  [[ -z "$(url_port "$url")" ]] || cli+=(-p "$(url_port "$url")")
  command -v "${cli[0]}" >/dev/null || die "No valkey-cli or redis-cli. Install one, or let ${subnet} reach Valkey by hand."
  RD_VERSION=$("${cli[@]}" info server 2>/dev/null | tr -d '\r' | grep -E '^(valkey_version|redis_version):' | head -1 | cut -d: -f2 || true)
  bind=$("${cli[@]}" config get bind 2>&1 | sed -n 2p | tr -d '\r')
  # CONFIG can be renamed or turned off. Then the script cannot see or change anything.
  [[ -n "$bind" ]] || die "Cannot read the Valkey config (CONFIG is turned off?). Add ${gw} to 'bind' by hand, or use --valkey docker."
  major=$(printf '%s' "$RD_VERSION" | cut -d. -f1)
  local todo=() newbind=""
  if [[ " $bind " != *" * "* && " $bind " != *" 0.0.0.0 "* && " $bind " != *"${gw}"* ]]; then
    # "-" = optional address (Valkey and Redis 7+): no failure when the bridge is missing.
    ((${major:-0} >= 7)) || die "Valkey/Redis ${RD_VERSION} cannot change 'bind' while it runs. Add ${gw} to 'bind' in its config, restart it, and run again."
    newbind="${bind} -${gw}"
    todo+=("bind: '${bind}' -> '${newbind}' (no restart)")
  fi
  # With no password, protected mode (Valkey, Redis 7+) refuses all clients that are not on
  # localhost, whatever 'bind' says. Find this before any change.
  local pmode
  pmode=$("${cli[@]}" config get protected-mode 2>/dev/null | sed -n 2p | tr -d '\r')
  if [[ -z "$pw" && "$pmode" == yes ]]; then
    todo+=("protected-mode: yes -> no (Valkey has no password; 'bind' still lets in only localhost and ${gw}). Better: give Valkey a password and set VALKEY_URL.")
  fi
  [[ -n "$(fw_name)" ]] && todo+=("$(fw_name): allow ${subnet} to ${gw} port 6379")
  if ((${#todo[@]})); then
    ask_change "Change Valkey" "Valkey/Redis on this server must let the Zerodot containers in:
$(printf ' - %s\n' "${todo[@]}")
${gw} is the Docker bridge. It is not on the internet." \
      || die "Valkey/Redis not changed. Make these changes by hand and run again (or add --allow-host-changes):
$(printf ' - %s\n' "${todo[@]}")"
    if [[ -n "$newbind" ]]; then
      "${cli[@]}" config set bind "$newbind" >/dev/null
      changed "Valkey/Redis: bind '${bind}' -> '${newbind}'"
      "${cli[@]}" config rewrite >/dev/null 2>&1 || note "Could not save 'bind' to the Valkey config file. Add -${gw} to 'bind' there, or it goes at the next restart."
    fi
    if [[ -z "$pw" && "$pmode" == yes ]]; then
      "${cli[@]}" config set protected-mode no >/dev/null
      "${cli[@]}" config rewrite >/dev/null 2>&1 || note "Could not save protected-mode to the Valkey config file."
      changed "Valkey/Redis: protected-mode yes -> no"
    fi
    [[ -z "$(fw_name)" ]] || fw_allow_from "$subnet" "$gw" 6379
  fi
  rd_check_policy "${cli[@]}"
  local unit
  unit=$(redis_unit || true)
  [[ -z "$unit" ]] || after_docker "${unit}.service"
  ok "Valkey/Redis lets the containers in"
}

# after_docker UNIT: start UNIT after Docker at boot. Only the order; it does not need Docker.
after_docker() {
  local d="/etc/systemd/system/$1.d"
  unit_exists "$1" || return 0
  [[ -f "$d/zerodot-docker.conf" ]] && return 0
  mkdir -p "$d"
  printf '# Added by Zerodot install.sh: listens on the Docker bridge address, which Docker makes.\n[Unit]\nAfter=docker.service\n' > "$d/zerodot-docker.conf"
  systemctl daemon-reload
  changed "systemd: $1 starts after docker.service ($d/zerodot-docker.conf)"
}

# docker_reach KIND URL DEFAULT_PORT: can a container open a connection to the database?
docker_reach() {
  local kind="$1" url="$2" host port out
  host=$(url_host "$url"); port=$(url_port "$url"); port="${port:-$3}"
  local js='const [h,p,k]=process.argv.slice(1);const s=require("net").connect(+p,h);s.setTimeout(5000);
s.on("connect",()=>{if(k==="valkey")s.write("PING\r\n");else{console.log("OK");process.exit(0)}});
s.on("data",d=>{const t=String(d);console.log(t.startsWith("-DENIED")?"DENIED":"OK");process.exit(t.startsWith("-DENIED")?3:0)});
s.on("timeout",()=>{console.log("TIMEOUT");process.exit(2)});s.on("error",e=>{console.log(e.code);process.exit(1)});'
  [[ "$url" == rediss://* ]] && kind=tcp
  out=$(docker compose run --rm --no-deps -T --entrypoint node api -e "$js" "$host" "$port" "$kind" 2>&1 | tail -1 || true)
  case "$out" in
    OK) ok "The containers reach $kind at ${host}:${port}" ;;
    DENIED) die "Valkey/Redis refuses the containers (protected mode, no password). Give it a password and set VALKEY_URL, or set 'protected-mode no'." ;;
    *) die "The containers cannot reach $kind at ${host}:${port} (${out:-no answer}). Check that it listens on the Docker bridge, and the firewall." ;;
  esac
}

wait_http() {
  local code _
  for _ in $(seq 1 60); do
    code=$(curl -s -o /dev/null -w '%{http_code}' "$1" || true)
    [[ "$code" =~ ^(200|307)$ ]] && return 0
    sleep 3
  done
  return 1
}

# ===========================================================================
# NATIVE MODE
# ===========================================================================
NODE_DIR=""
PNPM=""

ensure_node() {
  local cur="" real
  if command -v node >/dev/null && command -v npm >/dev/null; then
    cur=$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)
    real=$(readlink -f "$(command -v node)")
    # A Node in a home folder (nvm) cannot be read by the service user.
    if ((cur >= NODE_REQ)) && [[ "$real" != /root/* && "$real" != /home/* ]]; then
      NODE_DIR=$(dirname "$(dirname "$real")")
      ok "Using Node $(node -v) from $NODE_DIR"
      return
    fi
    note "Node $(node -v) does not fit (need ${NODE_REQ}+ outside a home folder). A private Node goes to /opt/zerodot-node. The system Node stays as it is."
  fi
  local arch idx file sum dest
  case "$(uname -m)" in x86_64) arch=x64 ;; aarch64) arch=arm64 ;; *) die "Unsupported CPU type." ;; esac
  # shellcheck disable=SC2046
  pkg_install $(pkgs_xz)
  idx=$(curl -fsSL "https://nodejs.org/dist/latest-v${NODE_REQ}.x/SHASUMS256.txt")
  file=$(printf '%s\n' "$idx" | awk -v a="linux-${arch}.tar.xz" '$2 ~ a"$" {print $2}' | head -1)
  sum=$(printf '%s\n' "$idx" | awk -v f="$file" '$2 == f {print $1}')
  [[ -n "$file" && -n "$sum" ]] || die "Cannot find Node ${NODE_REQ} for ${arch} on nodejs.org."
  dest="/opt/zerodot-node/${file%.tar.xz}"
  if [[ ! -x "$dest/bin/node" ]]; then
    say "Installing Node ${file%.tar.xz} to /opt/zerodot-node"
    mkdir -p /opt/zerodot-node
    curl -fsSL "https://nodejs.org/dist/latest-v${NODE_REQ}.x/${file}" -o "/tmp/${file}"
    (cd /tmp && printf '%s  %s\n' "$sum" "$file" | sha256sum -c - >/dev/null) || die "Node download failed the checksum."
    tar -xJf "/tmp/${file}" -C /opt/zerodot-node
    rm -f "/tmp/${file}"
  fi
  NODE_DIR="$dest"
  ok "Using private Node $("$NODE_DIR/bin/node" -v)"
}

ensure_pnpm() {
  local have=""
  command -v pnpm >/dev/null && have=$(PATH="$NODE_DIR/bin:$PATH" pnpm --version 2>/dev/null || true)
  if [[ "$have" == "$PM_VER" ]]; then
    PNPM=$(command -v pnpm)
    ok "Using pnpm $have"
    return
  fi
  [[ -n "$have" ]] && note "pnpm $have found; this repository needs exactly $PM_VER (the lockfile depends on it)."
  local prefix="/opt/zerodot-tools/pnpm-${PM_VER}"
  if [[ ! -x "$prefix/bin/pnpm" ]]; then
    say "Installing pnpm $PM_VER to $prefix"
    PATH="$NODE_DIR/bin:$PATH" npm install -g --silent --prefix "$prefix" "pnpm@${PM_VER}"
  fi
  PNPM="$prefix/bin/pnpm"
  ok "Using pnpm $PM_VER"
}

pg_run() { (cd / && runuser -u postgres -- psql -v ON_ERROR_STOP=1 -Atq "$@"); }

setup_postgres() {
  local url
  url=$(get_env DATABASE_URL)
  if [[ -n "${DATABASE_URL:-}" ]]; then set_env DATABASE_URL "$DATABASE_URL"; return; fi
  if [[ -n "$url" && "$url" == *"@127.0.0.1:"* ]]; then ok "Database: keeping DATABASE_URL from .env"; return; fi

  detect_postgres
  if [[ "$PG_STATE" == none ]]; then
    install_postgres
    detect_postgres
  fi
  pg_create_db
  set_env DATABASE_URL "postgres://${DBNAME}:${PG_NEW_PASS}@127.0.0.1:${PG_PORT}/${DBNAME}"
}

# Only when no Postgres is on the server. A data folder that exists is never set up again.
install_postgres() {
  say "Installing Postgres"
  local auth=(--auth-local=peer --auth-host=scram-sha-256)
  case "$OS_FAMILY" in
    debian) pkg_install postgresql ;; # Debian makes and starts the cluster.
    fedora | rhel)
      pkg_install postgresql-server postgresql
      if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
        PGSETUP_INITDB_OPTIONS="${auth[*]}" postgresql-setup --initdb >/dev/null
        changed "Postgres: new data folder /var/lib/pgsql/data"
      fi
      ;;
    arch)
      pkg_install postgresql
      if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
        (cd / && runuser -u postgres -- initdb -D /var/lib/postgres/data -E UTF8 --locale=C.UTF-8 "${auth[@]}" >/dev/null)
        changed "Postgres: new data folder /var/lib/postgres/data"
      fi
      ;;
  esac
  systemctl enable --now postgresql >/dev/null 2>&1 || true
  changed "Postgres: service enabled and started"
  local _
  for _ in $(seq 1 20); do detect_postgres; [[ "$PG_STATE" == running && "$PG_VERNUM" -gt 0 ]] && return 0; sleep 1; done
  die "Postgres did not start. See: journalctl -u postgresql -n 50"
}

# A new user and database named DBNAME on the Postgres of this server -> PG_NEW_PASS.
PG_NEW_PASS=""
pg_create_db() {
  detect_postgres
  [[ "$PG_STATE" == running ]] || die "Postgres is not running. Start it and run again."
  ((PG_VERNUM >= 130000)) || die "Postgres $((PG_VERNUM / 10000)) is too old (need 13+). Use the Postgres container, or set DATABASE_URL."
  if [[ "$(pg_run -c "select 1 from pg_roles where rolname='${DBNAME}'")" == 1 ]]; then
    die "A Postgres user '${DBNAME}' already exists but .env has no DATABASE_URL for it. Pick another --name, or set DATABASE_URL."
  fi
  PG_NEW_PASS=$(openssl rand -hex 24)
  pg_run -c "create role \"${DBNAME}\" login password '${PG_NEW_PASS}'"
  # The owner can make tables. Postgres 15+ does not let other users make tables in 'public'.
  [[ "$(pg_run -c "select 1 from pg_database where datname='${DBNAME}'")" == 1 ]] || pg_run -c "create database \"${DBNAME}\" owner \"${DBNAME}\""
  changed "Postgres: new user and database '${DBNAME}'"
  if ! PGPASSWORD="$PG_NEW_PASS" psql -h 127.0.0.1 -p "$PG_PORT" -U "$DBNAME" -d "$DBNAME" -Atqc 'select 1' >/dev/null 2>&1; then
    # Fedora and RHEL use 'ident' for 127.0.0.1. Add password lines for this user and database only.
    local hba method=scram-sha-256
    hba=$(pg_run -c 'show hba_file')
    [[ "$(pg_run -c 'show password_encryption')" == md5 ]] && method=md5
    pg_hba_add "$hba" "host ${DBNAME} ${DBNAME} 127.0.0.1/32 ${method}"
    pg_hba_add "$hba" "host ${DBNAME} ${DBNAME} ::1/128 ${method}"
    pg_run -c 'select pg_reload_conf()' >/dev/null
    sleep 1
    PGPASSWORD="$PG_NEW_PASS" psql -h 127.0.0.1 -p "$PG_PORT" -U "$DBNAME" -d "$DBNAME" -Atqc 'select 1' >/dev/null 2>&1 \
      || die "Created the database but cannot log in over TCP. Check pg_hba.conf ($hba) for 127.0.0.1."
  fi
  ok "Database '${DBNAME}' ready on Postgres $((PG_VERNUM / 10000))"
}

redis_unit() {
  local u
  for u in valkey-server valkey redis-server redis; do
    if unit_exists "${u}.service"; then echo "$u"; return 0; fi
  done
  return 0
}

setup_valkey() {
  local url
  url=$(get_env VALKEY_URL)
  if [[ -n "${VALKEY_URL:-}" ]]; then set_env VALKEY_URL "$VALKEY_URL"; return; fi
  if [[ -n "$url" && "$url" == *"127.0.0.1"* ]]; then ok "Queue: keeping VALKEY_URL from .env"; return; fi

  detect_redis
  if [[ "$RD_STATE" == none ]]; then
    # Only when no Valkey or Redis is on the server: then the config file is new and ours to set.
    say "Installing Valkey (or Redis)"
    local conf
    case "$PKG" in
      apt) pkg_first valkey-server valkey redis-server ;;
      *) pkg_first valkey redis ;;
    esac
    [[ -n "$REPLY" ]] || die "Valkey/Redis did not install. Install one by hand or set VALKEY_URL."
    for conf in /etc/valkey/valkey.conf /etc/redis/redis.conf /etc/redis.conf; do
      if [[ -f "$conf" ]]; then
        # The last line wins. The queue needs noeviction and a log on disk.
        printf '\n# Added by Zerodot install.sh\nmaxmemory-policy noeviction\nappendonly yes\nbind 127.0.0.1 -::1\n' >> "$conf"
        changed "Valkey/Redis: settings added to $conf"
        break
      fi
    done
    local unit
    unit=$(redis_unit || true)
    [[ -n "$unit" ]] || die "Valkey/Redis did not install. Install one by hand or set VALKEY_URL."
    systemctl enable "$unit" >/dev/null 2>&1 || true
    systemctl restart "$unit"
    changed "Valkey/Redis: service $unit enabled and started"
    sleep 2
    detect_redis
  fi
  [[ "$RD_STATE" == running ]] || die "Valkey/Redis is not running. Start it and run again."
  ((RD_AUTH == 0)) || die "Valkey/Redis on 6379 needs a password. Set VALKEY_URL=redis://:PASSWORD@127.0.0.1:6379/N and run again."
  [[ -z "$RD_CLI" ]] || rd_check_policy "$RD_CLI" -h 127.0.0.1

  redis_free_db
  set_env VALKEY_URL "redis://127.0.0.1:6379/${RD_DB}"
}

# Own database number, so other apps on a shared server are not touched -> RD_DB.
RD_DB=1
redis_free_db() {
  local n c="${RD_CLI:-redis-cli}"
  RD_DB=1
  if command -v "$c" >/dev/null; then
    for n in $(seq 1 15); do
      if [[ "$("$c" -h 127.0.0.1 -n "$n" dbsize 2>/dev/null | tr -d '\r')" == 0 ]]; then RD_DB="$n"; break; fi
    done
  fi
  ok "Queue ready (Valkey/Redis database number ${RD_DB})"
}

native_mode() {
  say "Checking tools for native mode"
  # isolated-vm (the code sandbox) is a native module.
  # shellcheck disable=SC2046
  pkg_install $(pkgs_build)
  ensure_node
  ensure_pnpm

  setup_postgres
  setup_valkey

  WEB_PORT=$(state_get "$DIR" WEB_PORT); API_PORT=$(state_get "$DIR" API_PORT)
  WORKER_PORT=$(state_get "$DIR" WORKER_PORT); SANDBOX_PORT=$(state_get "$DIR" SANDBOX_PORT)
  local old_web="" old_api=""
  if [[ "$WEB_PORT" =~ ^[0-9]+$ ]] && [[ -f "$STATE_FILE" ]]; then
    old_web="$WEB_PORT"; old_api="$API_PORT"
  else
    WEB_PORT=""; API_PORT=""; WORKER_PORT=""; SANDBOX_PORT=""
  fi
  # The ports given now win. The others stay, or get the first free one.
  RESERVED="$RESERVED $PORT_ARG $API_PORT_ARG $WORKER_PORT_ARG $SANDBOX_PORT_ARG"
  WEB_PORT="${PORT_ARG:-$WEB_PORT}"; API_PORT="${API_PORT_ARG:-$API_PORT}"
  WORKER_PORT="${WORKER_PORT_ARG:-$WORKER_PORT}"; SANDBOX_PORT="${SANDBOX_PORT_ARG:-$SANDBOX_PORT}"
  [[ -n "$WEB_PORT" ]] || { free_port 3000; WEB_PORT="$FREE_PORT"; }
  [[ -n "$API_PORT" ]] || { free_port 3003; API_PORT="$FREE_PORT"; }
  [[ -n "$WORKER_PORT" ]] || { free_port 3001; WORKER_PORT="$FREE_PORT"; }
  [[ -n "$SANDBOX_PORT" ]] || { free_port 3002; SANDBOX_PORT="$FREE_PORT"; }
  [[ -z "$old_web" ]] || moved_upstream "${OLD_UP_HOST}:${old_web}" "${UP_HOST}:${WEB_PORT}"
  [[ -z "$old_api" ]] || moved_upstream "127.0.0.1:${old_api}" "127.0.0.1:${API_PORT}"
  set_env SANDBOX_URL "http://127.0.0.1:${SANDBOX_PORT}"
  if [[ -n "$DATA_DIR" ]]; then
    set_env ZERODOT_BLOB_DIR "${DATA_DIR}/blobs"
    set_env ZERODOT_NODES_DIR "${DATA_DIR}/nodes"
  fi
  if [[ -n "$FILES_DIR_ARG" ]]; then
    mkdir -p "$FILES_DIR_ARG"
    chmod 750 "$FILES_DIR_ARG"
    set_env ZERODOT_FILES_DIR "$FILES_DIR_ARG"
  fi
  set_env_once ZERODOT_BLOB_DIR "/var/lib/${NAME}/blobs"
  # One folder for installed node packages: web runs in apps/web, api and worker in the root.
  set_env_once ZERODOT_NODES_DIR "/var/lib/${NAME}/nodes"

  say "Building (the first build takes about 10 minutes)"
  # Turborepo looks for pnpm on PATH, so the folder of the pinned pnpm goes there too.
  local pnpm_dir
  pnpm_dir=$(dirname "$PNPM")
  export PATH="$NODE_DIR/bin:$pnpm_dir:$PATH"
  export TURBO_TELEMETRY_DISABLED=1 DO_NOT_TRACK=1
  # GCC 13+ (Fedora 44 has GCC 16) does not include <cstdint> by itself. isolated-vm needs it.
  export CXXFLAGS="${CXXFLAGS:-} -include cstdint"
  "$PNPM" install --frozen-lockfile || die "pnpm install failed. Look at the messages above."
  # Node gives a process about 2 GB heap on servers with less than 16 GB RAM. The type build of
  # node-sdk needs more. Give it RAM plus swap minus 1 GB, between 2 and 4 GB. An own NODE_OPTIONS stays.
  if [[ "${NODE_OPTIONS:-}" != *max-old-space-size* ]]; then
    # Swap may be new: the script can add it. Read it again.
    local swap_now heap
    swap_now=$(awk '/SwapTotal/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)
    heap=$((MEM_MB + ${swap_now:-0} - 1024))
    ((heap >= 2048)) || heap=2048
    ((heap <= 4096)) || heap=4096
    export NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--max-old-space-size=${heap}"
  fi
  "$PNPM" run build || die "The build failed. Look at the messages above. Low memory is a common cause (check: free -m, dmesg | grep -i oom)."

  if ! id "$NAME" >/dev/null 2>&1; then
    useradd --system --user-group --home-dir "$DIR" --shell "$(nologin_shell)" "$NAME"
    changed "Added system user $NAME"
  fi
  local blob nodes
  nodes=$(get_env ZERODOT_NODES_DIR)
  if [[ -n "$nodes" && ! -d "$nodes" ]]; then mkdir -p "$nodes"; chown "$NAME:$NAME" "$nodes"; fi
  if [[ -n "$FILES_DIR_ARG" ]]; then chown "$NAME:$NAME" "$FILES_DIR_ARG"; fi
  blob=$(get_env ZERODOT_BLOB_DIR)
  chown -R "$NAME:$NAME" "$DIR"
  # A blob folder that you set and that exists can hold other files: only its top gets the owner.
  if [[ -d "$blob" && "$blob" != "/var/lib/${NAME}/blobs" ]]; then
    chown "$NAME:$NAME" "$blob"
  else
    mkdir -p "$blob"
    chown -R "$NAME:$NAME" "$blob"
  fi
  chown "root:$NAME" .env && chmod 640 .env
  # SELinux: systemd may not read a file with the label var_t (a new /var/www folder has it).
  # Give this one file the label etc_t, with a rule that stays after a relabel.
  if command -v selinuxenabled >/dev/null && selinuxenabled; then
    command -v semanage >/dev/null || pkg_install policycoreutils-python-utils
    if [[ "$(stat -c %C .env 2>/dev/null)" != *:etc_t:* ]]; then
      semanage fcontext -a -t etc_t "${DIR}/\.env" 2>/dev/null || semanage fcontext -m -t etc_t "${DIR}/\.env"
      restorecon "$DIR/.env"
      changed "SELinux: label etc_t on $DIR/.env, so systemd can read it (undo: semanage fcontext -d '${DIR}/\.env')"
    fi
  fi

  write_units
  systemctl daemon-reload
  systemctl enable "${NAME}-sandbox" "${NAME}-api" "${NAME}-worker" "${NAME}-web" >/dev/null 2>&1
  systemctl restart "${NAME}-sandbox" "${NAME}-api" "${NAME}-worker" "${NAME}-web"

  say "Waiting for the app on ${UP_HOST}:${WEB_PORT}"
  wait_http "http://${UP_HOST}:${WEB_PORT}/" || {
    systemctl --no-pager status "${NAME}-web" "${NAME}-api" | tail -20 || true
    die "The app did not start. See: journalctl -u ${NAME}-api -u ${NAME}-web -n 50"
  }
  changed "Services ${NAME}-web, -api, -worker, -sandbox installed and started"
  CADDY_KIND="split"
  UPSTREAM_PORT="$WEB_PORT"
  write_state WEB_PORT API_PORT WORKER_PORT SANDBOX_PORT
  chown "$NAME:$NAME" "$STATE_FILE"
}

write_units() {
  local after="network.target" vite
  local pg_unit="postgresql.service" rd_unit
  rd_unit="$(redis_unit || true)"
  [[ -n "$rd_unit" ]] && rd_unit="${rd_unit}.service"
  if unit_exists "$pg_unit"; then after="$after $pg_unit"; fi
  [[ -n "$rd_unit" ]] && after="$after $rd_unit"

  # Shared hardening. The API, worker and sandbox listen on localhost only.
  local common="User=${NAME}
Group=${NAME}
WorkingDirectory=${DIR}
Environment=PATH=${NODE_DIR}/bin:/usr/local/bin:/usr/bin:/bin
Environment=NODE_ENV=production
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true"

  cat > "/etc/systemd/system/${NAME}-sandbox.service" <<UNIT
[Unit]
Description=Zerodot code sandbox (${NAME})
After=network.target

[Service]
${common}
Environment=PORT=${SANDBOX_PORT}
Environment=ZERODOT_BIND_HOST=127.0.0.1
ExecStart=${NODE_DIR}/bin/node --no-node-snapshot apps/sandbox/dist/index.js

[Install]
WantedBy=multi-user.target
UNIT

  cat > "/etc/systemd/system/${NAME}-api.service" <<UNIT
[Unit]
Description=Zerodot API (${NAME})
After=${after}

[Service]
${common}
EnvironmentFile=${DIR}/.env
Environment=ZERODOT_API_PORT=${API_PORT}
Environment=ZERODOT_BIND_HOST=127.0.0.1
ExecStart=${NODE_DIR}/bin/node apps/api/dist/index.js

[Install]
WantedBy=multi-user.target
UNIT

  cat > "/etc/systemd/system/${NAME}-worker.service" <<UNIT
[Unit]
Description=Zerodot worker (${NAME})
After=${after} ${NAME}-sandbox.service

[Service]
${common}
EnvironmentFile=${DIR}/.env
Environment=PORT=${WORKER_PORT}
Environment=ZERODOT_BIND_HOST=127.0.0.1
ExecStart=${NODE_DIR}/bin/node apps/worker/dist/index.js

[Install]
WantedBy=multi-user.target
UNIT

  vite="node_modules/vite/bin/vite.js"
  [[ -f "apps/web/$vite" ]] || die "Cannot find Vite in apps/web after the build."
  cat > "/etc/systemd/system/${NAME}-web.service" <<UNIT
[Unit]
Description=Zerodot web (${NAME})
After=${after} ${NAME}-api.service

[Service]
${common}
WorkingDirectory=${DIR}/apps/web
EnvironmentFile=${DIR}/.env
# The web app also sends the API paths to the API, so one port serves all (for a tunnel).
Environment=ZERODOT_API_PORT=${API_PORT}
ExecStart=${NODE_DIR}/bin/node ${vite} preview --host ${BIND} --port ${WEB_PORT}

[Install]
WantedBy=multi-user.target
UNIT
}

CADDY_KIND="single"
UPSTREAM_PORT=""
if [[ "$MODE" == docker ]]; then docker_mode; else native_mode; fi

signup_text() {
  local admins signup
  admins=$(get_env ZERODOT_ADMIN_EMAILS)
  signup=$(get_env ZERODOT_SIGNUP_DISABLED)
  if [[ -n "$admins" ]]; then
    echo "  Sign up with an admin email ($admins). Those accounts are the instance admins."
  else
    echo "  Sign up first. The first user is the admin."
  fi
  if [[ "$signup" == true ]]; then
    echo "  Public signup is off. Invite the others from the project settings."
  else
    echo "  Then turn off public signup in System > Access (or run again with --disable-signup)."
  fi
}

# ---------------------------------------------------------------------------
# Step 7: proxy
# ---------------------------------------------------------------------------
# API paths, from the Caddyfile in the repository: the API takes these, the web app takes the rest.
api_paths=$(grep -m1 '@api path' Caddyfile | sed 's/^[[:space:]]*@api path //')

caddy_block() {
  # Plain HTTP: the http:// prefix stops Caddy from getting a certificate.
  local site="$DOMAIN"
  [[ "$SCHEME" == http ]] && site="http://$DOMAIN"
  if [[ "$CADDY_KIND" == split ]]; then
    printf '%s {\n\tencode gzip\n\t@api path %s\n\thandle @api {\n\t\treverse_proxy 127.0.0.1:%s {\n\t\t\tflush_interval -1\n\t\t}\n\t}\n\thandle {\n\t\treverse_proxy %s:%s\n\t}\n}' \
      "$site" "$api_paths" "$API_PORT" "$UP_HOST" "$WEB_PORT"
  else
    printf '%s {\n\tencode gzip\n\treverse_proxy %s:%s {\n\t\tflush_interval -1\n\t}\n}' "$site" "$UP_HOST" "$UPSTREAM_PORT"
  fi
}

nginx_block() {
  local p loc paths
  read -ra paths <<<"$api_paths"   # no glob: the paths hold '*'
  cat <<CONF
# Written by Zerodot install.sh (${NAME}). certbot adds the HTTPS part.
server {
    listen 80;
    listen [::]:80;
    server_name ${DOMAIN};

    client_max_body_size 100m;
    proxy_http_version 1.1;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto \$scheme;
    proxy_set_header X-Forwarded-Host \$host;
    proxy_set_header Connection "";
    # Live event streams must not wait for a full buffer.
    proxy_buffering off;
    proxy_read_timeout 1h;
    proxy_send_timeout 1h;
CONF
  if [[ "$CADDY_KIND" == split ]]; then
    for p in "${paths[@]}"; do
      # Caddy "/x/*" is a prefix, "/x" is one path.
      if [[ "$p" == */\* ]]; then loc="^~ ${p%\*}"; else loc="= $p"; fi
      printf '\n    location %s {\n        proxy_pass http://127.0.0.1:%s;\n    }\n' "$loc" "$API_PORT"
    done
    printf '\n    location / {\n        proxy_pass http://%s:%s;\n    }\n}\n' "$UP_HOST" "$WEB_PORT"
  else
    printf '\n    location / {\n        proxy_pass http://%s:%s;\n    }\n}\n' "$UP_HOST" "$UPSTREAM_PORT"
  fi
}

# repoint_proxy FILE: the app moved to another port or address. Change the upstreams in FILE.
repoint_proxy() {
  local m old new
  backup "$1"
  for m in "${MOVES[@]}"; do
    old="${m% *}"; new="${m#* }"
    # Only a whole port: 127.0.0.1:3000 but not 127.0.0.1:30001.
    sed -E -i.zerodot-tmp "s#${old//./\\.}([^0-9]|\$)#${new}\\1#g" "$1" && rm -f "$1.zerodot-tmp"
    changed "$(basename "$1"): upstream $old changed to $new"
  done
}

setup_caddy() {
  local block
  block=$(caddy_block)
  command -v caddy >/dev/null || install_caddy
  selinux_allow_proxy
  if [[ -f "$CADDYFILE" ]] && grep -Eq "(^|[[:space:],])(https?://)?${DOMAIN//./\\.}(:[0-9]+)?[[:space:]]*(,|\{)" "$CADDYFILE"; then
    if ((${#MOVES[@]})); then
      repoint_proxy "$CADDYFILE"
      caddy validate --config "$CADDYFILE" >/dev/null 2>&1 && svc_start caddy \
        || { cp -p "$BACKUP" "$CADDYFILE"; die "Caddy rejected the new port. Old Caddyfile restored. Change the port of ${DOMAIN} in $CADDYFILE by hand."; }
      return
    fi
    say "Caddy already has a block for ${DOMAIN}. Left as is."
    svc_active caddy || svc_start caddy
    return
  fi
  # A Caddyfile made by hand that Caddy cannot read: do not add to it.
  if [[ -s "$CADDYFILE" ]] && ! caddy validate --config "$CADDYFILE" >/dev/null 2>&1; then
    die "$CADDYFILE has an error already (caddy validate). The script does not change it. Fix it, or add this block by hand:
$block"
  fi
  say "Adding ${DOMAIN} to $CADDYFILE"
  mkdir -p "$(dirname "$CADDYFILE")"
  backup "$CADDYFILE"
  printf '\n%s\n' "$block" >> "$CADDYFILE"
  if caddy validate --config "$CADDYFILE" >/dev/null 2>&1 && svc_start caddy; then
    changed "Caddy: added a site for ${DOMAIN} to $CADDYFILE"
    echo "Caddy reloaded."
  else
    # Put the old file back so the other sites keep working.
    if [[ -n "$BACKUP" ]]; then cp -p "$BACKUP" "$CADDYFILE"; else : > "$CADDYFILE"; fi
    if ((IS_MAC)); then svc_active caddy && brew services restart caddy >/dev/null 2>&1 || true
    else systemctl reload caddy 2>/dev/null || true; fi
    die "Caddy rejected the new block. Old Caddyfile restored. Add this block by hand:
$block"
  fi
}

install_caddy() {
  say "Installing Caddy"
  if ((IS_MAC)); then
    command -v brew >/dev/null || die "Caddy on macOS comes from Homebrew (https://brew.sh). Install it, or use --proxy none."
    brew install caddy || die "brew install caddy failed."
    changed "Installed Caddy (Homebrew)"
    return
  fi
  case "$OS_FAMILY" in
    debian)
      pkg_install debian-keyring debian-archive-keyring apt-transport-https gnupg
      if [[ ! -f /etc/apt/sources.list.d/caddy-stable.list ]]; then
        curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
        curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' > /etc/apt/sources.list.d/caddy-stable.list
        changed "Added package repository /etc/apt/sources.list.d/caddy-stable.list"
        PKG_FRESH=0
      fi
      pkg_install caddy
      ;;
    fedora) pkg_install caddy ;;
    rhel)
      if ! pkg_available caddy; then
        ask_change "Caddy repository" "Caddy is not in the RHEL repositories. The script can turn on the Caddy COPR repository (@caddy/caddy)." \
          || die "Caddy not installed. Use --proxy nginx, or install Caddy yourself."
        pkg_install 'dnf-command(copr)'
        dnf copr enable -y @caddy/caddy >/dev/null
        changed "Turned on COPR repository @caddy/caddy"
      fi
      pkg_install caddy
      ;;
    arch) pkg_install caddy ;;
  esac
  command -v caddy >/dev/null || die "Caddy did not install."
}

setup_nginx() {
  local conf link="" other
  command -v nginx >/dev/null || { say "Installing nginx"; pkg_install nginx; }
  selinux_allow_proxy
  if [[ -d /etc/nginx/sites-available && -d /etc/nginx/sites-enabled ]]; then
    conf="/etc/nginx/sites-available/${NAME}.conf"; link="/etc/nginx/sites-enabled/${NAME}.conf"
  else
    conf="/etc/nginx/conf.d/${NAME}.conf"
  fi
  if [[ -f "$conf" ]] && ((${#MOVES[@]})); then
    # certbot may have changed it: change only the upstream.
    repoint_proxy "$conf"
    nginx -t >/dev/null 2>&1 && svc_start nginx \
      || { cp -p "$BACKUP" "$conf"; die "nginx rejected the new port. Old site restored. Change the port in $conf by hand."; }
  elif [[ -f "$conf" ]]; then
    # certbot may have changed it. Keep it.
    say "nginx site $conf exists. Left as is."
  else
    other=$(grep -rlsE "server_name[^;]*[[:space:]]${DOMAIN//./\\.}[[:space:];]" /etc/nginx/ || true)
    if [[ -n "$other" ]]; then
      say "nginx already has ${DOMAIN} in $(echo "$other" | head -1). Left as is."
      printf 'Make sure it sends traffic as in this site:\n\n%s\n\n' "$(nginx_block)"
      return
    fi
    # An nginx config with an error already: do not add to it.
    if ! nginx -t >/dev/null 2>&1; then
      die "nginx has an error already (nginx -t). The script does not change it. Fix it, or add this site by hand:
$(nginx_block)"
    fi
    say "Adding nginx site $conf"
    mkdir -p "$(dirname "$conf")"
    nginx_block > "$conf"
    [[ -z "$link" ]] || ln -sf "$conf" "$link"
    nginx_include "$conf" "$link" || { rm -f "$conf" ${link:+"$link"}; die "nginx site not added. See above."; }
    if ! nginx -t >/dev/null 2>&1; then
      rm -f "$conf" ${link:+"$link"}
      die "nginx rejected the new site (nginx -t). Removed it. Add this by hand:
$(nginx_block)"
    fi
    changed "nginx: added site $conf"
    svc_start nginx
  fi
  # HTTPS. certbot changes the site and renews the certificate on a timer.
  if grep -q 'ssl_certificate' "$conf" 2>/dev/null; then ok "nginx site has HTTPS"; return; fi
  if [[ "$SCHEME" == http ]]; then ok "Plain HTTP (no domain): no certificate"; return; fi
  if ((DO_CERTBOT)); then
    # shellcheck disable=SC2046
    if ! pkg_install $(pkgs_certbot); then
      note "certbot is not in the package repositories (RHEL: it is in EPEL). The site works on HTTP. Install certbot, then run: certbot --nginx -d ${DOMAIN}"
      return
    fi
    if certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --redirect \
      ${CERTBOT_EMAIL:+-m "$CERTBOT_EMAIL"} ${CERTBOT_EMAIL:---register-unsafely-without-email}; then
      changed "certbot: certificate for ${DOMAIN}, HTTPS added to $conf"
      ok "HTTPS on for ${DOMAIN}"
      certbot_timer
    else
      note "certbot failed (DNS not ready?). The site works on HTTP. Try later: certbot --nginx -d ${DOMAIN}"
    fi
  else
    note "No HTTPS yet. Sign-in needs HTTPS. Add a certificate to $conf."
  fi
}

# nginx_include FILE [LINK]: does nginx load the site? Arch nginx.conf loads no folder of sites:
# ask to add an include for conf.d. Returns 1 (with a message) when the site is not loaded.
nginx_include() {
  local main=/etc/nginx/nginx.conf dump
  dump=$(nginx -T 2>/dev/null || true)
  [[ "$dump" == *"# configuration file $1:"* ]] && return 0
  [[ -n "${2:-}" && "$dump" == *"# configuration file $2:"* ]] && return 0
  if [[ "$1" != /etc/nginx/conf.d/* ]]; then
    echo "nginx does not load $1. Add an include for it to $main, and run again." >&2
    return 1
  fi
  if ! ask_change "nginx.conf" "$main does not load /etc/nginx/conf.d/*.conf. The script can add this line in its http { } block:
    include /etc/nginx/conf.d/*.conf;"; then
    echo "nginx.conf not changed. Add 'include /etc/nginx/conf.d/*.conf;' to its http block, and run again (or add --allow-host-changes)." >&2
    return 1
  fi
  backup "$main"
  sed -i -E '0,/^[[:space:]]*http[[:space:]]*\{/s//&\n    include \/etc\/nginx\/conf.d\/*.conf;  # Added by Zerodot install.sh/' "$main"
  if ! nginx -t >/dev/null 2>&1; then
    cp -p "$BACKUP" "$main"
    echo "nginx rejected the include. $main restored." >&2
    return 1
  fi
  changed "nginx: added 'include /etc/nginx/conf.d/*.conf;' to $main"
}

# Renewal: Debian and Fedora packages have a certbot timer. Arch does not: add one.
certbot_timer() {
  local t
  for t in certbot.timer certbot-renew.timer snap.certbot.renew.timer; do
    if unit_exists "$t"; then systemctl enable --now "$t" >/dev/null 2>&1 || true; return 0; fi
  done
  unit_exists zerodot-certbot-renew.timer && return 0
  printf '[Unit]\nDescription=Renew Let'"'"'s Encrypt certificates (Zerodot install.sh)\n\n[Service]\nType=oneshot\nExecStart=%s renew --quiet --deploy-hook "systemctl reload nginx"\n' "$(command -v certbot)" \
    > /etc/systemd/system/zerodot-certbot-renew.service
  printf '[Unit]\nDescription=Renew certificates twice a day\n\n[Timer]\nOnCalendar=*-*-* 00,12:00:00\nRandomizedDelaySec=1h\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n' \
    > /etc/systemd/system/zerodot-certbot-renew.timer
  systemctl daemon-reload
  systemctl enable --now zerodot-certbot-renew.timer >/dev/null 2>&1
  changed "Added zerodot-certbot-renew.timer (certbot renew twice a day)"
}

install_cloudflared() {
  say "Installing cloudflared"
  case "$OS_FAMILY" in
    debian)
      if [[ ! -f /etc/apt/sources.list.d/cloudflared.list ]]; then
        install -d -m 0755 /usr/share/keyrings
        curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg -o /usr/share/keyrings/cloudflare-main.gpg
        echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main' > /etc/apt/sources.list.d/cloudflared.list
        changed "Added package repository /etc/apt/sources.list.d/cloudflared.list"
        PKG_FRESH=0
      fi
      pkg_install cloudflared
      ;;
    fedora | rhel)
      add_repo_file https://pkg.cloudflare.com/cloudflared.repo /etc/yum.repos.d/cloudflared.repo
      pkg_install cloudflared
      ;;
    arch) pkg_install cloudflared ;;
  esac
  command -v cloudflared >/dev/null || die "cloudflared did not install."
}

setup_cloudflared() {
  local target
  if [[ "$MODE" == docker ]] && ((TUNNEL_IN_DOCKER)); then
    target="http://proxy:3000"
    ok "Tunnel runs in the 'cloudflared' container"
  else
    target="http://${UP_HOST}:${UPSTREAM_PORT}"
    if unit_exists cloudflared.service; then
      ok "cloudflared already runs on this server. Add ${DOMAIN} to its tunnel (below)."
      ((${#MOVES[@]} == 0)) || note "The app moved to ${target}. Change the service of ${DOMAIN} in the tunnel."
    else
      [[ -n "$TUNNEL_TOKEN" ]] || TUNNEL_TOKEN=$(get_env ZERODOT_TUNNEL_TOKEN)
      ask_tunnel_token
      command -v cloudflared >/dev/null || install_cloudflared
      cloudflared service install "$TUNNEL_TOKEN" >/dev/null 2>&1 || die "cloudflared service install failed. Check the token."
      changed "cloudflared: service installed with the tunnel token"
      ok "cloudflared service installed"
    fi
  fi
  cat <<EOM

  Last step, in the Cloudflare dashboard:
    Zero Trust > Networks > Tunnels > your tunnel > Public hostname > Add
      Hostname:  ${DOMAIN}
      Service:   ${target}
  Cloudflare makes the DNS record. Requests longer than 100 s and uploads over 100 MB stop at Cloudflare.
EOM
}

# The port listens on 127.0.0.1 only, so a proxy in a container cannot reach it.
none_docker_hint() {
  if [[ "$MODE" == docker ]]; then
    local net
    net="$(docker compose config 2>/dev/null | sed -n 's/^name: //p' | head -1)_default"
    printf 'A proxy in Docker (Traefik, Nginx Proxy Manager): join this network and use http://proxy:3000\n  docker network connect %s <proxy container>' "$net"
  else
    printf 'A proxy in Docker cannot reach 127.0.0.1 on the host. Use a proxy on the host, or --proxy cloudflared.'
  fi
}

# Native mode: the web app also serves the API paths, so proxies with one upstream use the web port.
if [[ "$MODE" == native && "$PROXY" != caddy && "$PROXY" != nginx ]]; then UPSTREAM_PORT="$WEB_PORT"; fi
# --bind: the app port is open to the network. Native mode: let it through the firewall.
# (Docker publishes ports around ufw by itself.)
if [[ "$BIND" != 127.0.0.1 && "$MODE" == native ]] && ((DO_FIREWALL)) && ((IS_MAC == 0)); then
  if ufw_active; then ufw allow "${WEB_PORT}/tcp" >/dev/null && changed "ufw: allowed ${WEB_PORT}/tcp"
  elif firewalld_active; then fwd --add-port="${WEB_PORT}/tcp" && changed "firewalld: allowed ${WEB_PORT}/tcp"; fi
fi

case "$PROXY" in
  caddy) setup_caddy ;;
  nginx) setup_nginx ;;
  cloudflared) setup_cloudflared ;;
  none)
    say "Proxy: not changed"
    ((${#MOVES[@]} == 0)) || note "The app moved to http://${UP_HOST}:${UPSTREAM_PORT}. Change the upstream in your proxy."
    if [[ "$DOMAIN" == localhost:* ]]; then ok "Only this computer: no proxy needed"; else
    cat <<EOM
Send all traffic for ${DOMAIN} to http://${UP_HOST}:${UPSTREAM_PORT}
  - Keep the Host header, set X-Forwarded-For and X-Forwarded-Proto.
  - Turn off response buffering (live event streams) and allow long reads (1 hour).
  - Serve HTTPS: sign-in cookies need it.
$(none_docker_hint)

Caddy example:

$(caddy_block)

EOM
    fi
    ;;
esac

# ---------------------------------------------------------------------------
# Step 8: DNS check, for the proxies that get a certificate here.
# Cloudflare hides the IP, so this is only a warning.
# ---------------------------------------------------------------------------
if [[ "$PROXY" == caddy || "$PROXY" == nginx ]] && [[ "$SCHEME" == https ]]; then
  server_ip=$(curl -s4 --max-time 5 https://ifconfig.me || true)
  if ((IS_MAC)); then
    dns_ip=$(dscacheutil -q host -a name "$DOMAIN" 2>/dev/null | awk '/^ip_address:/ {print $2; exit}' || true)
  else
    dns_ip=$(getent ahostsv4 "$DOMAIN" | awk 'NR==1 {print $1}' || true)
  fi
  if [[ -z "$dns_ip" ]]; then
    note "${DOMAIN} has no IPv4 DNS record yet. Add: A ${DOMAIN} ${server_ip:-<this server IP>}"
  elif [[ -n "$server_ip" && "$dns_ip" != "$server_ip" ]]; then
    note "${DOMAIN} points to ${dns_ip}, this server is ${server_ip}. Fine if you use the Cloudflare proxy (SSL mode Full). Otherwise fix the A record."
  fi
fi

# Backups and updates.
install_cli
setup_jobs

say "Done"
# A Mac at home is behind a router: Caddy gets a certificate only when 80 and 443 reach it.
if ((IS_MAC)) && [[ "$PROXY" == caddy && "$SCHEME" == https ]]; then
  note "Forward ports 80 and 443 on your router to this Mac. Else Caddy gets no certificate. --proxy cloudflared needs no open ports."
fi
# The install is done. A run that stops before this line asks to continue or start again.
if [[ "$DONE" != 1 ]]; then
  DONE=1
  sed -i.zerodot-tmp 's/^DONE=.*/DONE=1/' "$DIR/$STATE_FILE" && rm -f "$DIR/$STATE_FILE.zerodot-tmp"
fi
if [[ "$MODE" == native ]]; then
  manage="systemctl restart ${NAME}-web ${NAME}-api ${NAME}-worker ${NAME}-sandbox    (logs: journalctl -u ${NAME}-api -f)"
else
  manage="cd ${DIR} && docker compose logs -f"
fi
if [[ "$MODE" == docker && "$PG_MODE" != docker ]]; then
  backup="pg_dump \"\$DATABASE_URL\" (the database is outside Docker)"
elif [[ "$MODE" == docker ]]; then
  backup="cd ${DIR} && docker compose exec -T postgres pg_dump -U zerodot zerodot | gzip > zerodot-\$(date +%F).sql.gz"
else
  backup="runuser -u postgres -- pg_dump ${DBNAME} | gzip > ${NAME}-\$(date +%F).sql.gz"
fi
# The zerodot lines only when the command is installed. NAME is needed when there are more installs.
sfx=""
(($(other_installs) > 0)) && sfx=" ${NAME}"
if [[ -f "$(cli_path)" ]]; then
  update_line="  Update later:  zerodot update${sfx}"
  manage_line="  Manage:        zerodot status${sfx} | logs${sfx} | restart${sfx} | backup${sfx} (zerodot help)
  Without it:    ${manage}"
  uninstall_line="zerodot uninstall${sfx}"
else
  update_line="  Update later:  $( ((IS_MAC)) || echo "sudo ")bash ${DIR}/scripts/install.sh ${DOMAIN}"
  manage_line="  Manage:        ${manage}"
  uninstall_line="$( ((IS_MAC)) || echo "sudo ")bash ${DIR}/scripts/install.sh ${DOMAIN} --uninstall"
fi
# A new install: how to sign in, and the key to keep. An update: only the version change.
if [[ "$ACTION" == update && "$FRESH_ENV" != true ]]; then
  now_version=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' "$DIR/package.json" | head -1)
  if [[ -n "$CUR_VERSION" && "$CUR_VERSION" != "$now_version" ]]; then first_lines="  Updated: ${CUR_VERSION} to ${now_version}"
  else first_lines="  Version: ${now_version:-unknown} (no new release)"; fi
else
  first_lines="$(signup_text)

  Save this key somewhere safe. If you lose it, saved credentials cannot be opened:
    ZERODOT_SECRET_KEY in ${DIR}/.env"
fi
cat <<EOM

  Open:    ${SCHEME}://${DOMAIN}
${first_lines}

${update_line}
${manage_line}
  Back up:       ${backup}
EOM
[[ "$BACKUP" == off ]] || echo "  Backups:       ${BACKUP}, in ${BACKUP_DIR} (newest ${BACKUP_KEEP})"
[[ "$AUTO_UPDATE" == off ]] || echo "  Auto-update:   ${AUTO_UPDATE}$( ((IS_MAC)) && echo " (log: ~/Library/Logs/${NAME}-update.log)" || echo " (log: journalctl -u ${NAME}-update)")"
[[ -z "$VERSION" ]] || echo "  Release:       ${VERSION} (fixed). Follow new releases: --version latest"
[[ "$BIND" == 127.0.0.1 ]] || echo "  Also open on:  http://${BIND}:${UPSTREAM_PORT} (plain HTTP)"
echo "  Uninstall:     ${uninstall_line}"
[[ "$PROXY" != cloudflared ]] || echo "  The address works after you add the public hostname in Cloudflare (see above)."
[[ "$PROXY" != none || "$DOMAIN" == localhost:* ]] || echo "  The address works after you add the rule to your proxy (see above)."
if ((IS_MAC)); then
  echo "  Keep it running: start Docker Desktop (or OrbStack) at login, and stop the Mac from sleeping."
  echo "  The containers start again with Docker."
fi
cat <<EOM

EOM
