#!/usr/bin/env bash
# Zender v5.0 one-shot installer
# ────────────────────────────────────────────────────────────────────────────
# Bootstraps nginx + PHP-FPM 8.4 + MySQL 8 + Laravel Reverb + Let's Encrypt SSL
# on a fresh Ubuntu 24.04 host.
#
# The WhatsApp-unofficial backend (the in-house `titansys-whatsapp-linux` Go binary)
# is deployed separately; see the zender-whatsapp repo.
#
# Usage:
#     sudo bash autosetup.sh [--dry-run] [--skip-ssl]
#     sudo DOMAIN=chat.example.com [CF_API_TOKEN=...] [CERTBOT_EMAIL=you@example.com] [ADMIN_EMAIL=you@example.com] bash autosetup.sh
#
# Features:
#   • Idempotent, safe to re-run
#   • Resume-aware, checkpoints in /var/lib/zender/setup-state
#   • Credential-generating, APP_KEY, JWT_SECRET, webhook secrets, DB pass
#   • --dry-run prints every action without executing
#
# Bundles (extracted per step 75 plan):
#   1. Base port (this file, from webby/autosetup.sh)
#   2. Reverb systemd delta (zender-reverb.service)
#   3. SSL (Let's Encrypt: HTTP validation, or a wildcard via Cloudflare DNS when CF_API_TOKEN is set)

set -euo pipefail

# ─── Configuration ──────────────────────────────────────────────────────────
ZENDER_USER="${ZENDER_USER:-zender}"
ZENDER_HOME="/var/www/zender"
STATE_DIR="/var/lib/zender"
STATE_FILE="${STATE_DIR}/setup-state"
PHP_VERSION="8.4"
NODE_VERSION="22"
REVERB_PORT="${REVERB_PORT:-8080}"
DRY_RUN=false
SKIP_SSL=false

# ─── Arg parsing ────────────────────────────────────────────────────────────
for arg in "$@"; do
    case "$arg" in
        --dry-run)   DRY_RUN=true ;;
        --skip-ssl)  SKIP_SSL=true ;;
        *) echo "Unknown flag: $arg" >&2; exit 1 ;;
    esac
done
SITE_SCHEME=https
$SKIP_SSL && SITE_SCHEME=http

# ─── Helpers ────────────────────────────────────────────────────────────────
log() { printf "\033[1;32m[zender]\033[0m %s\n" "$*"; }
warn() { printf "\033[1;33m[zender]\033[0m %s\n" "$*" >&2; }
die() { printf "\033[1;31m[zender]\033[0m %s\n" "$*" >&2; exit 1; }

run() {
    if $DRY_RUN; then
        echo "  $ $*"
    else
        eval "$@"
    fi
}

write_config() {
    if $DRY_RUN; then
        echo "  $ write $1"
        cat
    else
        cat > "$1"
    fi
}

check_step() {
    [[ -f "$STATE_FILE" ]] && grep -q "^$1$" "$STATE_FILE" 2>/dev/null
}

mark_step() {
    $DRY_RUN && return 0
    mkdir -p "$STATE_DIR"
    grep -q "^$1$" "$STATE_FILE" 2>/dev/null || echo "$1" >> "$STATE_FILE"
}

random_secret() {
    openssl rand -hex 32
}

require_root() {
    [[ $EUID -eq 0 ]] || die "This script must run as root. Try: sudo bash $0"
}

# ─── Bundle 1: base system setup ────────────────────────────────────────────
step_apt_update() {
    check_step "apt_update" && return 0
    # A freshly provisioned VPS is often still running cloud-init and its package
    # upgrades, which hold the apt locks. Wait for it instead of failing on step one.
    log "Waiting for first-boot provisioning to finish"
    run "command -v cloud-init >/dev/null && cloud-init status --wait >/dev/null; true"
    write_config /etc/apt/apt.conf.d/99zender-lock-timeout <<'EOF'
DPkg::Lock::Timeout "600";
EOF
    log "Updating apt cache"
    # apt-get update does not honour the timeout above for its lists lock.
    run "for attempt in \$(seq 1 30); do apt-get update -qq && break; [ \"\$attempt\" -lt 30 ] || exit 1; sleep 10; done"
    mark_step "apt_update"
}

step_system_packages() {
    check_step "system_packages" && return 0
    log "Installing base packages (nginx, mysql, certbot, php-fpm, ffmpeg)"
    # ffmpeg remuxes browser voice notes (WebM) to Ogg/Opus for WhatsApp.
    run "DEBIAN_FRONTEND=noninteractive apt-get install -y \
        nginx mysql-server certbot python3-certbot-dns-cloudflare python3-certbot-nginx \
        git curl unzip ca-certificates lsb-release software-properties-common \
        supervisor ffmpeg"
    mark_step "system_packages"
}

step_php() {
    check_step "php_${PHP_VERSION}" && return 0
    log "Installing PHP ${PHP_VERSION} + extensions"
    run "add-apt-repository -y ppa:ondrej/php"
    run "apt-get update -qq"
    run "apt-get install -y \
        php${PHP_VERSION}-fpm php${PHP_VERSION}-cli \
        php${PHP_VERSION}-mysql \
        php${PHP_VERSION}-mbstring php${PHP_VERSION}-xml \
        php${PHP_VERSION}-curl php${PHP_VERSION}-zip \
        php${PHP_VERSION}-bcmath php${PHP_VERSION}-gd \
        php${PHP_VERSION}-intl php${PHP_VERSION}-opcache"
    run "curl -sS https://getcomposer.org/installer | /usr/bin/php${PHP_VERSION} -- --install-dir=/usr/local/bin --filename=composer"
    mark_step "php_${PHP_VERSION}"
}

# A dedicated pool running as ${ZENDER_USER}, because the default pool runs as
# www-data while step_app_deploy chowns the whole tree to ${ZENDER_USER}. PHP-FPM
# could not then write storage/logs, storage/framework/{sessions,views,cache} or
# bootstrap/cache, so Laravel 500s on the first request that tries to log, open
# a session or compile a view, which is the first request. Every other process
# here already runs as ${ZENDER_USER}: both systemd units set User=, and
# composer/artisan/npm all go through sudo -u. FPM was the one exception.
#
# The alternative, adding www-data to the group and loosening storage, leaves
# two users writing the same tree, so files created by the web request end up
# unwritable by the CLI and vice versa. One user for everything is simpler and
# matches how this installer already works.
#
# The upload limits live here too: PHP defaults to 2M upload_max_filesize and 8M
# post_max_size, which silently truncates MMS and WhatsApp media and rejects any
# contact CSV of consequence. php_admin_value cannot be overridden at runtime by
# a buyer's plugin, which is what we want for the limits that bound uploads.
#
# 128M rather than a round 64M because the application's own validation rules
# decide the floor, not taste: Waba/MediaController accepts `max:102400` on two
# endpoints, 100M, annotated "Meta's hard limit for documents", so a pool
# capped below that makes a legitimate, Meta-supported document send fail at the
# platform instead of at validation, with $_FILES empty and the request looking
# as though no file was attached. The extra headroom over 100M covers multipart
# overhead, and post_max_size must be at least upload_max_filesize.
step_php_pool() {
    check_step "php_pool" && return 0
    log "Installing PHP-FPM pool for ${ZENDER_USER}"
    if ! $DRY_RUN; then
        cat > "/etc/php/${PHP_VERSION}/fpm/pool.d/zender.conf" <<EOF
[zender]
user = ${ZENDER_USER}
group = ${ZENDER_USER}
listen = /run/php/php${PHP_VERSION}-fpm-zender.sock
; nginx runs as www-data and has to be able to open the socket, even though the
; worker behind it runs as ${ZENDER_USER}.
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 8
pm.max_requests = 500
php_admin_value[upload_max_filesize] = 128M
php_admin_value[post_max_size] = 128M
php_admin_value[memory_limit] = 512M
php_admin_value[max_execution_time] = 120
EOF
    fi
    run "systemctl restart php${PHP_VERSION}-fpm"
    mark_step "php_pool"
}

step_node() {
    check_step "node_${NODE_VERSION}" && return 0
    log "Installing Node.js ${NODE_VERSION}"
    run "curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash -"
    run "apt-get install -y nodejs"
    mark_step "node_${NODE_VERSION}"
}

step_zender_user() {
    check_step "zender_user" && return 0
    log "Creating ${ZENDER_USER} system user"
    run "id ${ZENDER_USER} &>/dev/null || useradd -r -s /bin/bash -d ${ZENDER_HOME} -m ${ZENDER_USER}"
    mark_step "zender_user"
}

step_database() {
    check_step "database" && return 0
    log "Creating MySQL database + user"
    local db_pass
    db_pass=$(random_secret)
    run "mysql -e 'CREATE DATABASE IF NOT EXISTS zender CHARACTER SET utf8mb4;'"
    run "mysql -e \"CREATE USER IF NOT EXISTS 'zender'@'localhost' IDENTIFIED BY '${db_pass}';\""
    run "mysql -e \"GRANT ALL ON zender.* TO 'zender'@'localhost';\""
    run "mysql -e 'FLUSH PRIVILEGES;'"
    if ! $DRY_RUN; then
        echo "DB_PASSWORD=${db_pass}" > "${STATE_DIR}/db-credentials"
        chmod 600 "${STATE_DIR}/db-credentials"
    fi
    mark_step "database"
}

step_app_deploy() {
    check_step "app_deploy" && return 0
    log "Deploying Zender to ${ZENDER_HOME}"
    run "mkdir -p ${ZENDER_HOME}"
    run "cd ${ZENDER_HOME} && chown -R ${ZENDER_USER}:${ZENDER_USER} ."
    # In a real run, clone/pull from source repo here.
    # For fresh installs, we assume the admin has rsynced the release package.
    mark_step "app_deploy"
}

step_env_file() {
    check_step "env_file" && return 0
    log "Generating .env"
    # "Not yet configured" is the condition, not "no .env". RELEASE.md Step 10
    # writes Install/.env into the release ZIP as a copy of .env.example, so the
    # file already exists the moment a buyer extracts the archive, and this
    # block used to test only for its absence. Everything below was therefore
    # skipped on the primary install path: no key:generate (APP_KEY stays empty,
    # and Laravel refuses to serve a request without it), no database
    # credentials, no APP_ENV/APP_DEBUG, no Reverb credentials.
    #
    # An empty APP_KEY is the reliable signal, but it has to be read as a value
    # rather than matched as a pattern: .env.example writes
    # `APP_KEY=<spaces># php artisan key:generate`, so a plain `^APP_KEY=.+`
    # matches the trailing comment and calls a pristine file configured. The
    # value is therefore extracted, the comment stripped and whitespace removed
    # before testing. key:generate is the only thing that fills it, so a
    # genuinely configured install is still skipped on a re-run, which is what
    # the original guard was protecting.
    local env_file="${ZENDER_HOME}/.env"
    local needs_config=false
    if [[ ! -f "$env_file" ]]; then
        needs_config=true
    elif [[ -z "$(sed -n 's/^APP_KEY=//p' "$env_file" | sed 's/#.*//' | tr -d '[:space:]')" ]]; then
        needs_config=true
        log "Found an unconfigured .env (empty APP_KEY), configuring it"
    fi

    if ! $DRY_RUN && $needs_config; then
        [[ -f "$env_file" ]] || cp "${ZENDER_HOME}/.env.example" "$env_file"
        /usr/bin/php${PHP_VERSION} "${ZENDER_HOME}/artisan" key:generate --force
        # APP_URL is not cosmetic: config/filesystems.php builds the public
        # disk's URL as rtrim(APP_URL,'/').'/storage', so every branding logo,
        # image-library asset, landing image and thumbnail is served from it.
        # Hard-coding localhost pointed all of them at the VISITOR'S machine on
        # every buyer install. It also drives signed URLs and any URL generated
        # outside a request (queued mail, notifications). Nothing else ever sets
        # it, InstallerController only creates the admin user and writes
        # storage/installed.marker, so whatever is written here is final.
        # ${DOMAIN} is the same variable step_ssl and the closing banner use.
        if $SKIP_SSL; then
            sed -i "s|^APP_URL=.*|APP_URL=http://${DOMAIN:-localhost}|" "${ZENDER_HOME}/.env"
        else
            sed -i "s|^APP_URL=.*|APP_URL=https://${DOMAIN:-localhost}|" "${ZENDER_HOME}/.env"
        fi
        # .env.example ships APP_ENV=local and APP_DEBUG=true because it is also
        # the developer template. Nothing overrode them here and nothing
        # overrides them at runtime, unlike the mail settings, which
        # AppServiceProvider rebinds from SystemSetting, so every buyer install
        # ran in debug mode. Laravel's debug handler renders the whole
        # environment on any unhandled exception: DB_PASSWORD, APP_KEY, JWT
        # secret and whatever payment-gateway keys the buyer has configured, to
        # whoever triggered the error. That is a credential disclosure on a
        # public host, not a cosmetic default.
        sed -i "s|^APP_ENV=.*|APP_ENV=production|" "${ZENDER_HOME}/.env"
        sed -i "s|^APP_DEBUG=.*|APP_DEBUG=false|" "${ZENDER_HOME}/.env"
        # .env.example says "error in prod" next to this and nothing acted on it.
        # Debug level logs every query binding and the full request context, so a
        # production install was writing credentials-adjacent data to
        # storage/logs and growing it without limit.
        sed -i "s|^LOG_LEVEL=.*|LOG_LEVEL=error|" "${ZENDER_HOME}/.env"
        # Secure session cookies, but only when this install actually has TLS.
        # step_ssl provisions Let's Encrypt unless --skip-ssl was passed; with
        # the flag set there is no HTTPS listener, and a Secure cookie is never
        # returned to the browser over plain HTTP, so every login would appear
        # to succeed and then bounce straight back to the login form.
        if $SKIP_SSL; then
            warn "--skip-ssl: leaving SESSION_SECURE_COOKIE=false. Set it to true once TLS is in front of this install."
        else
            sed -i "s|^SESSION_SECURE_COOKIE=.*|SESSION_SECURE_COOKIE=true|" "${ZENDER_HOME}/.env"
        fi
        # MAIL_MAILER is deliberately left alone: AppServiceProvider binds
        # mail.default from SystemSetting, so the admin panel's email settings
        # win over whatever .env says once configured.

        # Without this the three DB_ lines below are inert. .env.example ships
        # DB_CONNECTION=sqlite because that is the development default, and
        # nothing here overrode it, so the installer created the MySQL database
        # and user above (CREATE DATABASE zender / CREATE USER 'zender'), wrote
        # their credentials into .env, and then left Laravel reading a SQLite
        # connection that ignores all three. The MySQL database sat empty on
        # every buyer install while the app looked for database/database.sqlite,
        # which is excluded from the release ZIP and therefore absent.
        # Two ways that surfaces, both bad: migrate fails outright on the missing
        # file, or a stray SQLite file makes it "work" on the wrong engine,
        # where enum columns become CHECK constraints rather than MySQL's strict
        # ENUM, so schema bugs only ever reproduce in production.
        sed -i "s|^DB_CONNECTION=.*|DB_CONNECTION=mysql|" "${ZENDER_HOME}/.env"
        sed -i "s|^DB_DATABASE=.*|DB_DATABASE=zender|" "${ZENDER_HOME}/.env"
        sed -i "s|^DB_USERNAME=.*|DB_USERNAME=zender|" "${ZENDER_HOME}/.env"
        [[ -f "${STATE_DIR}/db-credentials" ]] && \
            sed -i "s|^DB_PASSWORD=.*|DB_PASSWORD=$(grep DB_PASSWORD ${STATE_DIR}/db-credentials | cut -d= -f2)|" "${ZENDER_HOME}/.env"
        sed -i "s|^JWT_SECRET=.*|JWT_SECRET=$(random_secret)|" "${ZENDER_HOME}/.env"
        sed -i "s|^CACHE_STORE=.*|CACHE_STORE=database|" "${ZENDER_HOME}/.env"
        sed -i "s|^QUEUE_CONNECTION=.*|QUEUE_CONNECTION=database|" "${ZENDER_HOME}/.env"
    fi
    # This step runs as root and step_app_deploy already chowned the tree, so a
    # .env created here by cp stays root:root 0644: world-readable APP_KEY,
    # JWT_SECRET and the database password. Hand it to the service user, owner
    # and group only.
    if ! $DRY_RUN && [[ -f "${ZENDER_HOME}/.env" ]]; then
        chown "${ZENDER_USER}:${ZENDER_USER}" "${ZENDER_HOME}/.env"
        chmod 640 "${ZENDER_HOME}/.env"
    fi
    mark_step "env_file"
}

step_app_bootstrap() {
    check_step "app_bootstrap" && return 0
    log "composer install + migrate + npm build"
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} composer install --no-dev --optimize-autoloader --no-interaction"
    # --seed, not just --force. The documented manual install is
    # `php artisan migrate --seed`; this ran without it, so DatabaseSeeder never
    # executed on an autosetup install and nothing else supplies its rows, no
    # migration inserts data (checked: zero of them do). A buyer was left with no
    # subscription plans, so nobody could subscribe to anything; no language rows.
    #
    # Safe here only because APP_ENV=production is set above: UserSeeder returns
    # early on production unless ZENDER_ALLOW_USER_SEED_IN_PROD is set,
    # specifically so a seed cannot create the admin@example.com / "password"
    # demo account. While APP_ENV was left at .env.example's `local`, that guard
    # was inert, adding --seed then would have installed a backdoor with a
    # published password on every buyer install. Do not add --seed back if the
    # APP_ENV line is ever removed.
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} env CHANNEL_PLUGINS_CORE_ONLY=1 /usr/bin/php${PHP_VERSION} artisan migrate --force --seed"
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} /usr/bin/php${PHP_VERSION} artisan channel-plugins:sync"
    # Realtime settings live in system_settings, never .env, write them
    # straight into the database with zender:configure-realtime (mirrors
    # Webby's configure_reverb_settings). Public host/port/scheme is what the
    # BROWSER connects to: reverb:start binds 127.0.0.1 only, so that has to
    # be the domain over nginx (443/https, a ws:// connection from an
    # https:// page is blocked as mixed content before it is even tried).
    # server-host/server-port is the INTERNAL endpoint Laravel itself
    # publishes to (SettingsBroadcaster::configureReverb) and defaults to
    # 127.0.0.1:8080 when omitted; app-id/key/secret are generated by the
    # command itself when omitted. Empty credentials do not error, the
    # WebSocket handshake simply never authenticates, which presents as live
    # inbox updates, campaign progress and WhatsApp QR pairing silently not
    # working, and QR pairing is the only way to connect a WhatsApp account.
    local realtime_port=443 realtime_scheme=https
    if $SKIP_SSL; then
        realtime_port=80
        realtime_scheme=http
    fi
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} /usr/bin/php${PHP_VERSION} artisan zender:configure-realtime \
        --driver=reverb --host=${DOMAIN:-localhost} --port=${realtime_port} --scheme=${realtime_scheme} \
        --server-host=127.0.0.1 --server-port=${REVERB_PORT}"
    # The public disk (config/filesystems.php) serves branding logos, the image
    # library, landing images, thumbnails and public wa-media through
    # APP_URL/storage, which resolves ONLY through this symlink. It is not in
    # the release package, .release-exclude strips /public/storage precisely
    # because it is a machine-local absolute symlink, and nothing else in the
    # product creates it: not composer's post-install scripts, not any npm
    # script, and not InstallerController (which writes installed.marker and
    # checks storage writability, nothing more). Without this line every one of
    # those assets 404s on a fresh install.
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} /usr/bin/php${PHP_VERSION} artisan storage:link"
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} npm ci && sudo -u ${ZENDER_USER} npm run build"
    mark_step "app_bootstrap"
}

# NOTE: the WhatsApp-unofficial backend is the in-house `zender-whatsapp`
# Go binary (titansys-whatsapp-linux), registered per-server in the Zender admin
# (/wa/servers/create) and run separately with its own config.json. It is
# intentionally NOT provisioned by this installer.

# ─── Bundle 3: Reverb systemd delta ─────────────────────────────────────────
# Creates the administrator and marks the install complete, as the web
# installer's last step does, so the site is ready to sign in to. The web
# installer stays for manual installs. The login is kept root-only in
# ${STATE_DIR}/admin-credentials and printed when the script ends.
step_admin() {
    check_step "admin" && return 0
    log "Creating the administrator"
    local admin_email="${ADMIN_EMAIL:-admin@${DOMAIN:-example.com}}"
    local admin_password
    admin_password=$(openssl rand -hex 8)
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} env ZENDER_ADMIN_PASSWORD='${admin_password}' /usr/bin/php${PHP_VERSION} artisan zender:install-admin --email='${admin_email}'"
    if ! $DRY_RUN; then
        printf 'ADMIN_EMAIL=%s\nADMIN_PASSWORD=%s\n' "$admin_email" "$admin_password" > "${STATE_DIR}/admin-credentials"
        chmod 600 "${STATE_DIR}/admin-credentials"
    fi
    mark_step "admin"
}

step_reverb() {
    check_step "reverb" && return 0
    log "Installing Reverb systemd unit"

    # No --port flag: BroadcastConfigServiceProvider hydrates
    # reverb.servers.reverb.port from reverb_server_port in system_settings
    # (written by zender:configure-realtime above) on every console boot,
    # this process included. --host stays a CLI flag because it is a bind
    # decision (loopback only, behind nginx), not a value settings own.
    write_config /etc/systemd/system/zender-reverb.service <<EOF
[Unit]
Description=Zender Reverb WebSocket Server
After=network.target mysql.service

[Service]
Type=simple
User=${ZENDER_USER}
Group=${ZENDER_USER}
WorkingDirectory=${ZENDER_HOME}
ExecStart=/usr/bin/php${PHP_VERSION} artisan reverb:start --host=127.0.0.1
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

    run "systemctl daemon-reload"
    run "systemctl enable zender-reverb.service"
    run "systemctl start zender-reverb.service"
    mark_step "reverb"
}

step_queue_worker() {
    check_step "queue_worker" && return 0
    log "Installing queue worker systemd unit"

    write_config /etc/systemd/system/zender-queue.service <<EOF
[Unit]
Description=Zender Queue Worker
After=network.target mysql.service

[Service]
Type=simple
User=${ZENDER_USER}
Group=${ZENDER_USER}
WorkingDirectory=${ZENDER_HOME}
ExecStart=/usr/bin/php${PHP_VERSION} artisan queue:work --tries=3 --timeout=300
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    run "systemctl daemon-reload"
    run "systemctl enable zender-queue.service"
    run "systemctl start zender-queue.service"
    mark_step "queue_worker"
}

step_scheduler() {
    check_step "scheduler" && return 0
    log "Installing scheduler cron entry"
    # Appending is only safe once. check_step normally prevents a second run, but
    # the marker lives in /var/lib/zender and a buyer retrying a failed install
    # may well clear it, at which point an unguarded append installs schedule:run
    # twice and every scheduled job fires twice a minute. Grep the existing
    # crontab first so the step is idempotent on its own, not just via the marker.
    if crontab -u "${ZENDER_USER}" -l 2>/dev/null | grep -qF "${ZENDER_HOME} && /usr/bin/php${PHP_VERSION} artisan schedule:run"; then
        log "Scheduler cron entry already present, leaving it alone"
    else
        # php${PHP_VERSION} rather than bare php: cron runs with a minimal PATH,
        # and on a server that already had a PHP the default alternative may not
        # be the version this installer provisioned and pinned FPM to.
        # `|| true`: on a fresh server `crontab -l` exits 1 (no crontab yet). The subshell inherits
        # set -e, so without it the subshell quit before the echo, an empty crontab was installed and
        # pipefail ended the whole install here, before nginx.
        run "(crontab -u ${ZENDER_USER} -l 2>/dev/null || true; echo '* * * * * cd ${ZENDER_HOME} && /usr/bin/php${PHP_VERSION} artisan schedule:run >> /dev/null 2>&1') | crontab -u ${ZENDER_USER} -"
    fi
    mark_step "scheduler"
}

step_nginx() {
    check_step "nginx" && return 0
    log "Configuring nginx"

    write_config /etc/nginx/sites-available/zender <<EOF
map \$request_uri \$zender_frame_options {
    default "SAMEORIGIN";
    ~^/widget/frame/ "";
    ~^/f/[A-Za-z0-9]+(\?|\$) "";
}

server {
    # default_server keeps this the catch-all (workspace subdomains, custom domains) when
    # another site, such as the telephony service's host, is added to the same nginx.
    listen 80 default_server;
    server_name _;
    # step_ssl writes zender-tls.conf once a certificate exists; the glob matches nothing until then.
    include /etc/nginx/zender-tls*.conf;
    root ${ZENDER_HOME}/public;

    # 'always' is required: without it nginx applies add_header only to 2xx/3xx,
    # so error pages (404/500, and anything nginx serves before PHP is reached)
    # ship with no security headers at all. SecurityHeaders middleware cannot
    # cover those, it never runs for static assets or nginx-generated errors.
    # X-XSS-Protection is deliberately NOT emitted here (nor in the
    # custom-domain site template, see step_custom_domains); see the
    # SecurityHeaders docblock: it is deprecated and modern browsers ignore it.
    add_header X-Frame-Options \$zender_frame_options always;
    add_header X-Content-Type-Options "nosniff" always;

    # Match the PHP pool's limits explicitly. step_php_pool raises
    # upload_max_filesize/post_max_size to 128M and max_execution_time to 120,
    # but nginx sits in front and enforces its own ceilings, so PHP's values are
    # only reachable if nginx allows at least as much. Leaving these unset means
    # whatever nginx's compiled-in defaults are silently govern instead, and
    # they are lower than both, so the pool settings become unreachable:
    #
    #   - an upload larger than nginx's body limit is rejected with 413 before
    #     PHP is ever invoked, which the contact importer accepts up to 50M
    #     (ContactImportController: 'max:51200') and MMS/WhatsApp media needs
    #   - a request running longer than nginx's fastcgi read timeout returns 504
    #     while PHP keeps working, so the operator sees a failure for something
    #     that actually completed. Measured: importing a 50M CSV
    #     (1.1M rows) takes 62.8s, which is past the customary 60s default.
    #
    # Setting both explicitly is right regardless of what those defaults happen
    # to be on a given nginx build, the two layers should agree because someone
    # chose the numbers, not because they happen to line up.
    client_max_body_size 128M;

    index index.php;
    charset utf-8;

    # Compress text assets (the stock nginx.conf compresses text/html only) and let browsers keep the
    # hashed Vite bundles: a first load is several times smaller on slow links. expires, not add_header,
    # so the server-level security headers still apply to these responses.
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml application/xml;

    location ^~ /build/assets/ {
        try_files \$uri =404;
        expires 1y;
        access_log off;
    }

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    # Reverb serves the WebSocket at /app/{key} and the publish API at
    # /apps/{id}/events, those paths are fixed by the Pusher protocol, and
    # nothing tells the client to use anything else: resources/js/lib/echo.ts
    # passes wsHost/wsPort and no wsPath. This used to proxy /reverb/ only, a
    # path no client ever requests, so realtime could not work through nginx
    # while the config looked deliberate. reverb:start binds 127.0.0.1, so the
    # browser cannot reach it any other way either.
    # Trailing slash: Reverb's socket path is /app/{key}; a bare /app prefix would also catch /apps/{slot}.
    location /app/ {
        proxy_pass http://127.0.0.1:${REVERB_PORT};
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_read_timeout 86400;
    }

    # Reverb's HTTP API only: the app's own /apps/{slot} downloads must reach Laravel.
    location ~ ^/apps/[^/]+/(events|batch_events|channels|connections|users)(/|\$) {
        proxy_pass http://127.0.0.1:${REVERB_PORT};
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    # Only the front controller executes PHP; stored files must never execute.
    location = /index.php {
        fastcgi_pass unix:/run/php/php${PHP_VERSION}-fpm-zender.sock;
        # Headroom for large response headers (cookies, preload links); the defaults are 4 to 8 KB.
        fastcgi_buffer_size 32k;
        fastcgi_buffers 16 16k;
        # Must be >= the pool's max_execution_time (120), or nginx 504s a request
        # PHP is still legitimately working on. See the note above the body-size
        # limit for the measurement that motivates it.
        fastcgi_read_timeout 120s;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ \.php\$ { return 404; }

    # The prefix skips server regex locations, so deny scripts and dotfiles here.
    # Signed storage URLs are Laravel routes and need the front controller.
    location ^~ /storage/ {
        try_files \$uri /index.php?\$query_string;
        location ~ \.(php|phtml|phar|pht|phps|cgi|pl|py|sh)\$ { return 404; }
        location ~ /\. { deny all; }
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
EOF

    run "ln -sf /etc/nginx/sites-available/zender /etc/nginx/sites-enabled/zender"
    run "rm -f /etc/nginx/sites-enabled/default"
    # A reload keeps the old workers alive until their connections close, and
    # the Reverb proxy above holds WebSockets open for up to a day. Custom
    # domain changes reload nginx, so cap how long old workers may linger or
    # every reload piles up another set. Main-context directive: nginx.conf.
    run "grep -q '^worker_shutdown_timeout' /etc/nginx/nginx.conf || sed -i '/^worker_processes/a worker_shutdown_timeout 30s;' /etc/nginx/nginx.conf"
    run "nginx -t"
    run "systemctl reload nginx"
    mark_step "nginx"
}

# ─── Custom Messenger domains: certbot + nginx helpers ──────────────────────
# A workspace can serve its Messenger on its own domain (messenger.acme.com).
# `php artisan messenger-domain:provision-ssl`, run every minute by the
# scheduler as ${ZENDER_USER}, issues each verified domain's certificate and
# installs its nginx site. It needs root for that, and gets it only through two
# root-owned helper scripts plus a narrow sudoers file (ported from Webby).
#
# The helpers exist because sudoers cannot express the constraint needed. Sudo
# matches arguments as one concatenated string, so a rule like
# "certbot certonly --nginx -d *" is also satisfied by
# "-d example.com --pre-hook '<command>'", and certbot's hook flags run their
# argument as root. A wildcard path rule has the same hole: it matches "/", so
# "rm /etc/nginx/sites-available/zender-*" accepts a "zender-../../.." path.
# Each helper takes one domain, validates it, and builds every path itself, so
# no caller-supplied string ever reaches a privileged command as a path. The
# site helper also renders the vhost itself, from a root-owned template this
# step writes to /etc/zender, so no caller-supplied config body is installed.
step_custom_domains() {
    check_step "custom_domains" && return 0
    log "Installing custom-domain SSL helpers"

    # certbot --nginx needs the nginx plugin; the base packages only carry the
    # Cloudflare DNS plugin used for the platform's own wildcard.
    run "DEBIAN_FRONTEND=noninteractive apt-get install -y python3-certbot-nginx"

    if $DRY_RUN; then
        echo "  $ write /etc/zender/nginx-custom-domain.conf.tpl, /usr/local/bin/zender-certbot, /usr/local/bin/zender-nginx-site, /etc/sudoers.d/zender-ssl"
        mark_step "custom_domains"
        return 0
    fi

    # Resolve the real binaries so the sudoers rules match what sudo runs:
    # certbot may be /usr/bin/certbot (apt) or /snap/bin/certbot (snap), and a
    # rule for the wrong path is silently void ("a terminal is required").
    local CERTBOT_BIN NGINX_BIN
    CERTBOT_BIN="$(command -v certbot || echo /usr/bin/certbot)"
    NGINX_BIN="$(command -v nginx || echo /usr/sbin/nginx)"

    cat > /usr/local/bin/zender-certbot <<EOF
#!/bin/bash
# Obtains a certificate for one validated Messenger domain.
# Generated by autosetup.sh. Do not grant the web user certbot directly.
set -euo pipefail

if [[ \$# -ne 1 ]]; then
    echo "usage: \${0##*/} <domain>" >&2
    exit 64
fi

domain=\$1

if [[ \${#domain} -gt 253 ]] || ! [[ \$domain =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+\$ ]]; then
    echo "refusing to request a certificate for an invalid domain" >&2
    exit 65
fi

exec $CERTBOT_BIN certonly \\
    --nginx \\
    -d "\$domain" \\
    --non-interactive \\
    --agree-tos \\
    --keep-until-expiring \\
    --register-unsafely-without-email
EOF

    # The vhost template the site helper renders, one per custom domain. It
    # mirrors the main vhost in step_nginx (root, PHP-FPM pool socket, body and
    # timeout limits, the Reverb proxy paths, server-level security headers
    # with `always`) for one exact hostname, no www pairing. Root-owned, so the
    # web user can neither edit it nor hand the helper a config of its own.
    # Everything but the domain is fixed here, at install time; the helper
    # substitutes only __DOMAIN__, which it has already validated.
    install -d -o root -g root -m 0755 /etc/zender
    cat > /etc/zender/nginx-custom-domain.conf.tpl <<'TPL'
# Reuses the frame-options map from the main site in sites-enabled.
# Messenger custom domain: __DOMAIN__
# Rendered by /usr/local/bin/zender-nginx-site. Generated by autosetup.sh.
server {
    listen 80;
    listen [::]:80;
    server_name __DOMAIN__;

    add_header X-Frame-Options $zender_frame_options always;

    location /.well-known/acme-challenge/ {
        root __ROOT__;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name __DOMAIN__;
    root __ROOT__;

    ssl_certificate /etc/letsencrypt/live/__DOMAIN__/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/__DOMAIN__/privkey.pem;

    add_header X-Frame-Options $zender_frame_options always;
    add_header X-Content-Type-Options "nosniff" always;

    client_max_body_size 128M;

    index index.php;
    charset utf-8;

    # Compress text assets (the stock nginx.conf compresses text/html only) and let browsers keep the
    # hashed Vite bundles: a first load is several times smaller on slow links. expires, not add_header,
    # so the server-level security headers still apply to these responses.
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml application/xml;

    location ^~ /build/assets/ {
        try_files $uri =404;
        expires 1y;
        access_log off;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Trailing slash: Reverb's socket path is /app/{key}; a bare /app prefix would also catch /apps/{slot}.
    location /app/ {
        proxy_pass http://127.0.0.1:__REVERB_PORT__;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 86400;
    }

    # Reverb's HTTP API only: the app's own /apps/{slot} downloads must reach Laravel.
    location ~ ^/apps/[^/]+/(events|batch_events|channels|connections|users)(/|$) {
        proxy_pass http://127.0.0.1:__REVERB_PORT__;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    # Only the front controller executes PHP; stored files must never execute.
    location = /index.php {
        fastcgi_pass unix:__PHP_SOCKET__;
        # Headroom for large response headers (cookies, preload links); the defaults are 4 to 8 KB.
        fastcgi_buffer_size 32k;
        fastcgi_buffers 16 16k;
        fastcgi_read_timeout 120s;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ \.php$ { return 404; }

    # The prefix skips server regex locations, so deny scripts and dotfiles here.
    # Signed storage URLs are Laravel routes and need the front controller.
    location ^~ /storage/ {
        try_files $uri /index.php?$query_string;
        location ~ \.(php|phtml|phar|pht|phps|cgi|pl|py|sh)$ { return 404; }
        location ~ /\. { deny all; }
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
TPL
    sed -i \
        -e "s#__ROOT__#${ZENDER_HOME}/public#g" \
        -e "s#__PHP_SOCKET__#/run/php/php${PHP_VERSION}-fpm-zender.sock#g" \
        -e "s#__REVERB_PORT__#${REVERB_PORT}#g" \
        /etc/zender/nginx-custom-domain.conf.tpl
    chown root:root /etc/zender/nginx-custom-domain.conf.tpl
    chmod 0644 /etc/zender/nginx-custom-domain.conf.tpl

    cat > /usr/local/bin/zender-nginx-site <<'EOF'
#!/bin/bash
# Installs or removes one validated Messenger domain's nginx site.
# Generated by autosetup.sh. Do not grant the web user mv/ln/rm on /etc/nginx.
# The site is rendered here from the root-owned template. The caller passes
# only an action and a domain, never a file, a path or a config body.
set -euo pipefail

if [[ $# -ne 2 ]]; then
    echo "usage: ${0##*/} <install|remove> <domain>" >&2
    exit 64
fi

action=$1
domain=$2

if [[ ${#domain} -gt 253 ]] || ! [[ $domain =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]]; then
    echo "refusing to act on an invalid domain" >&2
    exit 65
fi

# Every path is fixed here or built from the validated domain.
template="/etc/zender/nginx-custom-domain.conf.tpl"
available="/etc/nginx/sites-available/zender-${domain}.conf"
enabled="/etc/nginx/sites-enabled/zender-${domain}.conf"

case "$action" in
    install)
        if [[ -L $template || ! -f $template ]]; then
            echo "missing site template at $template" >&2
            exit 66
        fi
        # Without its certificate the site would fail nginx -t for every site.
        if [[ ! -f /etc/letsencrypt/live/${domain}/fullchain.pem ]]; then
            echo "no certificate for $domain" >&2
            exit 66
        fi
        # Render next to the destination (a root-only directory), then move it
        # into place atomically. The domain matched the pattern above, so it
        # holds no character sed would treat specially.
        tmp="$(mktemp /etc/nginx/sites-available/.zender-XXXXXX)"
        trap 'rm -f -- "$tmp"' EXIT
        sed "s/__DOMAIN__/${domain}/g" "$template" > "$tmp"
        chown root:root "$tmp"
        chmod 0644 "$tmp"
        mv -f -- "$tmp" "$available"
        trap - EXIT
        ln -sfn -- "$available" "$enabled"
        ;;
    remove)
        rm -f -- "$enabled" "$available"
        ;;
    *)
        echo "unknown action: $action" >&2
        exit 64
        ;;
esac
EOF

    chown root:root /usr/local/bin/zender-certbot /usr/local/bin/zender-nginx-site
    chmod 0755 /usr/local/bin/zender-certbot /usr/local/bin/zender-nginx-site

    # Only the helpers, plus the two nginx subcommands that take no variable
    # arguments and so can be matched exactly. PHP-FPM and the scheduler run as
    # ${ZENDER_USER}, not www-data (see step_php_pool / step_scheduler).
    cat > /etc/sudoers.d/zender-ssl <<EOF
# Custom Messenger domain SSL provisioning (generated by autosetup.sh).
# ${ZENDER_USER} reaches privileged work only through the two root-owned
# helpers below, which validate their input.
${ZENDER_USER} ALL=(root) NOPASSWD: /usr/local/bin/zender-certbot
${ZENDER_USER} ALL=(root) NOPASSWD: /usr/local/bin/zender-nginx-site
${ZENDER_USER} ALL=(root) NOPASSWD: $NGINX_BIN -t
${ZENDER_USER} ALL=(root) NOPASSWD: $NGINX_BIN -s reload
EOF

    chmod 0440 /etc/sudoers.d/zender-ssl

    # A malformed sudoers file can break sudo entirely: validate it, and remove
    # it rather than leave a broken or silently ignored rule behind. Non-fatal:
    # custom domains are optional and the rest of the install must finish.
    if ! visudo -cf /etc/sudoers.d/zender-ssl >/dev/null 2>&1; then
        rm -f /etc/sudoers.d/zender-ssl
        warn "Generated /etc/sudoers.d/zender-ssl failed validation and was removed."
        warn "  Custom domain SSL will not be issued until this step succeeds."
        return 0
    fi

    mark_step "custom_domains"
    log "Custom domain SSL helpers installed (certbot: ${CERTBOT_BIN})"
}

# ─── Bundle 4: Let's Encrypt SSL ────────────────────────────────────────────
apply_site_scheme() {
    local scheme="$1" realtime_port=443 secure_cookie=true
    if [[ "$scheme" == http ]]; then
        realtime_port=80
        secure_cookie=false
    fi
    run "sed -i 's|^APP_URL=.*|APP_URL=${scheme}://${DOMAIN:-localhost}|' ${ZENDER_HOME}/.env"
    run "sed -i 's|^SESSION_SECURE_COOKIE=.*|SESSION_SECURE_COOKIE=${secure_cookie}|' ${ZENDER_HOME}/.env"
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} /usr/bin/php${PHP_VERSION} artisan zender:configure-realtime \
        --driver=reverb --host=${DOMAIN:-localhost} --port=${realtime_port} --scheme=${scheme} \
        --server-host=127.0.0.1 --server-port=${REVERB_PORT}"
    run "cd ${ZENDER_HOME} && sudo -u ${ZENDER_USER} /usr/bin/php${PHP_VERSION} artisan config:clear"
    SITE_SCHEME="$scheme"
}

step_ssl() {
    $SKIP_SSL && { log "Skipping SSL (--skip-ssl)"; return 0; }
    check_step "ssl" && return 0

    if [[ -z "${DOMAIN:-}" ]]; then
        warn "DOMAIN not set, skipping SSL. The site stays on HTTP; set DOMAIN and re-run autosetup.sh to add HTTPS."
        apply_site_scheme http
        return 0
    fi

    local email_args="--register-unsafely-without-email"
    if [[ -n "${CERTBOT_EMAIL:-}" ]]; then
        email_args="--email ${CERTBOT_EMAIL}"
    fi
    local tls_hosts="domain"
    if [[ -n "${CF_API_TOKEN:-}" ]]; then
        log "Let's Encrypt wildcard SSL for ${DOMAIN} via Cloudflare DNS"
        tls_hosts="wildcard"
        run "mkdir -p /etc/letsencrypt/cloudflare"
        if ! $DRY_RUN; then
            echo "dns_cloudflare_api_token = ${CF_API_TOKEN}" > /etc/letsencrypt/cloudflare/credentials.ini
            chmod 600 /etc/letsencrypt/cloudflare/credentials.ini
        fi

        if ! run "certbot certonly --dns-cloudflare \
            --dns-cloudflare-credentials /etc/letsencrypt/cloudflare/credentials.ini \
            --cert-name ${DOMAIN} -d ${DOMAIN} -d '*.${DOMAIN}' \
            --non-interactive --agree-tos ${email_args} --deploy-hook 'systemctl reload nginx'"; then
            warn "Could not get a certificate for ${DOMAIN}. Check that CF_API_TOKEN can edit DNS for this zone, then re-run autosetup.sh."
            warn "The site stays on HTTP until then."
            apply_site_scheme http
            return 0
        fi
    else
        log "Let's Encrypt SSL for ${DOMAIN} (HTTP validation)"
        warn "Workspace subdomains (*.${DOMAIN}) stay on HTTP. For a wildcard certificate, set CF_API_TOKEN and re-run autosetup.sh."
        if ! run "certbot certonly --webroot -w ${ZENDER_HOME}/public \
            --cert-name ${DOMAIN} -d ${DOMAIN} \
            --non-interactive --agree-tos ${email_args} --deploy-hook 'systemctl reload nginx'"; then
            warn "Could not get a certificate for ${DOMAIN}. Check that its DNS points to this server and port 80 is open, then re-run autosetup.sh."
            warn "The site stays on HTTP until then."
            apply_site_scheme http
            return 0
        fi
    fi

    local DOMAIN_RE="${DOMAIN//./\\.}"
    local redirect_pattern="^http:${DOMAIN_RE}$"
    if [[ "$tls_hosts" == wildcard ]]; then
        redirect_pattern="^http:(.+\.)?${DOMAIN_RE}$"
    fi
    # Let's Encrypt follows this redirect for webroot renewals. Redirect only
    # hosts the certificate covers; custom Messenger domains have their own sites.
    write_config /etc/nginx/zender-tls.conf <<EOF
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
set \$zender_tls_redirect "\$scheme:\$host";
if (\$zender_tls_redirect ~* "${redirect_pattern}") {
    return 301 https://\$host\$request_uri;
}
EOF

    # A TLS block nginx rejects must not stay behind: the next reload anywhere would fail.
    if ! run "nginx -t"; then
        run "rm -f /etc/nginx/zender-tls.conf"
        warn "nginx rejected the TLS configuration. The site stays on HTTP; re-run autosetup.sh after fixing nginx."
        apply_site_scheme http
        return 0
    fi
    run "systemctl reload nginx"
    apply_site_scheme https
    log "HTTPS enabled for ${DOMAIN}"
    mark_step "ssl"
}

# ─── Main ───────────────────────────────────────────────────────────────────
main() {
    require_root
    # DRY_RUN is always set (true or false), so ${DRY_RUN:+...} would print the suffix on every run.
    local mode=""
    $DRY_RUN && mode=" (DRY RUN)"
    log "Zender v5.0 autosetup starting${mode}"

    step_apt_update
    step_system_packages
    step_php
    step_node
    step_zender_user
    step_php_pool
    step_database
    step_app_deploy
    step_env_file
    step_app_bootstrap
    step_admin
    step_reverb
    step_queue_worker
    step_scheduler
    step_nginx
    step_custom_domains
    step_ssl

    log "✓ Setup complete. Save the details below somewhere safe."
    log ""
    log "  SITE"
    log "  • URL:       ${SITE_SCHEME}://${DOMAIN:-localhost}"
    log "  • App root:  ${ZENDER_HOME}"
    log "  • Logs:      journalctl -u zender-reverb -u zender-queue"
    if [[ -f "${STATE_DIR}/admin-credentials" ]]; then
        log ""
        log "  ADMIN LOGIN"
        log "  • Sign in:   ${SITE_SCHEME}://${DOMAIN:-localhost}/login"
        log "  • Email:     $(sed -n 's/^ADMIN_EMAIL=//p' "${STATE_DIR}/admin-credentials")"
        log "  • Password:  $(sed -n 's/^ADMIN_PASSWORD=//p' "${STATE_DIR}/admin-credentials")"
        log "    Change the password after signing in."
    fi
    if [[ -f "${STATE_DIR}/db-credentials" ]]; then
        log ""
        log "  DATABASE (MySQL)"
        log "  • Host:      127.0.0.1"
        log "  • Port:      3306"
        log "  • Database:  zender"
        log "  • Username:  zender"
        log "  • Password:  $(sed -n 's/^DB_PASSWORD=//p' "${STATE_DIR}/db-credentials")"
        log "  • MySQL root: run sudo mysql on the server (no password)"
    fi
    log ""
    log "  Saved, readable by root only: ${STATE_DIR}/admin-credentials, ${STATE_DIR}/db-credentials"
}

main
