#!/usr/bin/env bash # LicensePanel installer — Linux. Per contracts/installer.md. # # Branches: # • online first install — generates KEK + Postgres TLS + bootstrap cert, # writes panel-stack compose, `docker compose up -d` # • idempotent re-run — detects existing state.db, pulls latest image, # `docker compose up -d`, no state mutation # # Output never includes secrets (FR-007). Cloud-init logs respect the same # redaction. set -euo pipefail # ============================================================================ # Constants # ============================================================================ readonly PANEL_DIR="${PANEL_INSTALL_ROOT:-/var/lib/licensepanel}" # state.db lives inside data/ so the panel's nonroot UID (1654) can open it # AND create the sibling licensepanel-dataprotection-keys/ dir there. The # parent $PANEL_DIR is root-owned; only $DATA_DIR is owned by 1654. readonly STATE_DB="$PANEL_DIR/data/state.db" readonly KEYS_DIR="$PANEL_DIR/keys" readonly POSTGRES_TLS_DIR="$PANEL_DIR/postgres-tls" readonly TRAEFIK_DIR="$PANEL_DIR/traefik" readonly DATA_DIR="$PANEL_DIR/data" readonly COMPOSE_DIR="$PANEL_DIR/panel-stack" readonly COMPOSE_FILE="$COMPOSE_DIR/docker-compose.yml" readonly ENV_FILE="$COMPOSE_DIR/.env" readonly DEFAULT_VERSION="latest" readonly DEFAULT_IMAGE_REPO="registry.innovation-lab.co/modern-solutions/licensepanel" # Canonical install host (Dokploy service). Overridable per render / environment. readonly INSTALLER_LIB_URL="${LICENSEPANEL_INSTALL_BASE:-https://license-install.mod-sol-sa.com}" # BASH_SOURCE[0] is empty when the script is piped from `curl | bash` (no file # on stdin); the `:-` default keeps `set -u` from aborting. In piped mode this # resolves to a non-existent dir, so resolve_lib() falls through to downloading. readonly LIB_DIR_LOCAL="$(cd "$(dirname "${BASH_SOURCE[0]:-}")" && pwd)/lib" # Exit codes readonly EXIT_SUCCESS=0 readonly EXIT_GENERIC=1 readonly EXIT_PREFLIGHT=2 readonly EXIT_DOCKER_INSTALL=3 # 4 reserved (was AIRGAP_INVALID; air-gap install isn't shipped in R1). readonly EXIT_PERMISSIONS=5 readonly EXIT_FINGERPRINT=6 readonly EXIT_TLS=7 readonly EXIT_COMPOSE=8 # ============================================================================ # Flag parsing # ============================================================================ panel_host="" acme_email="" no_docker=0 panel_version="$DEFAULT_VERSION" panel_image_repo="$DEFAULT_IMAGE_REPO" no_start=0 # --reset --yes wipes /var/lib/licensepanel AND the docker named volumes # before fresh-installing. Two flags required so it cannot trigger by accident. reset=0 yes_flag=0 # DNS-01 ACME — set --acme-dns-provider to opt into DNS-based cert issuance # (Let's Encrypt without an open port 80). When set, the bundled Traefik is # rendered with the DNS-01 challenge instead of HTTP-01. acme_dns_provider="" acme_dns_env=() # Empty = auto. Edge ports prefer 80/443 (needed for Let's Encrypt HTTP-01 and # standard-port customer access) but fall back to a free port when those are # taken — so `curl … | sudo bash` on a Dokploy/nginx/CDN-occupied host still # installs. The direct panel-access port prefers 8443 and auto-picks too. # An explicit non-empty override is treated as a pin: hard-fail if in use. http_port="${LICENSEPANEL_HTTP_PORT:-}" https_port="${LICENSEPANEL_HTTPS_PORT:-}" panel_port="${LICENSEPANEL_PANEL_PORT:-}" # Deferred HTTP-01 tip flag. Set in resolve_ports when the edge auto-picks # a non-standard port (so HTTP-01 cannot work on the bundled Traefik), then # evaluated late in main — AFTER the panel reports healthy — so we can read # /var/lib/licensepanel/data/edge.json. If the panel's EdgeAutoDetect landed # on mode=external, the bundled Traefik is a pass-through and won't be # issuing customer certs at all, so the tip is misleading. See 1.5.1 task 7. WARN_HTTP01=0 # LicenseServer integration (Mod-Sol licensing back-end). BaseUrl defaults to # the public license-api host. No API key is required: the panel self-registers # a free-tier license by fingerprint on first boot and authenticates every # LicenseServer call with the panel-license-token JWT it manages. BaseUrl can # be set via env (LICENSEPANEL_LS_BASE_URL) for non-interactive automation or # self-hosted license-server installs. license_server_base_url="${LICENSEPANEL_LS_BASE_URL:-https://license-api.mod-sol-sa.com}" # Host public IP for sslip.io-style generated domains. Detected automatically # on first install (curl ipify / ifconfig.me); overridable via --server-ip for # air-gapped or NATted hosts where the detection would return a private address. server_ip="" # Orchestration backend selection (plan T16). `--backend dokploy` provisions the # panel ON Dokploy (Dokploy owns the edge + lifecycle); the default is `dokploy` # on Linux unless `--air-gapped` (which forces the self-contained compose edge). # `--expose-dokploy-dashboard` keeps Dokploy's :3000 published (default: sealed). # The dokploy path delegates to infra/installer/lib/dokploy-shim.sh; the full # host-bootstrap + `bootstrap-dokploy` exec (which needs the registry login from # T17 to pull the private panel image) lands with T17. backend="" air_gapped=0 expose_dokploy_dashboard=0 dokploy_api_key="" registry_url="${LICENSEPANEL_REGISTRY_URL:-}" registry_user="${LICENSEPANEL_REGISTRY_USER:-}" registry_token="${LICENSEPANEL_REGISTRY_TOKEN:-}" registry_image_prefix="${LICENSEPANEL_REGISTRY_IMAGE_PREFIX:-}" # DKB-REG T7 — the customer types only their license: --license + # --activation-code fetch the private-registry pull credential from the # LicenseServer registry-bootstrap endpoint BEFORE the panel pull. Manual # --registry-* override this license path. license_serial="${LICENSEPANEL_LICENSE:-}" activation_code="${LICENSEPANEL_ACTIVATION_CODE:-}" print_help() { cat <<'EOF' LicensePanel installer Usage: curl -sSL https://license-install.mod-sol-sa.com/install.sh | sudo bash curl -sSL https://license-install.mod-sol-sa.com/install.sh | sudo bash -s -- [flags] No flag is required. Bare `curl … | sudo bash` lands in bootstrap mode (self-signed cert on the direct-access port); finish setup — domain, ACME email, challenge type, DNS provider, DNS credentials — in Initial Configuration in the browser. The flags below are pre-seeds: anything you pass here is what you'd otherwise type in IC. Flags (all optional): --panel-host Pre-seed the panel host (engages ACME at first boot when --acme-email is also given). --server-ip Public IP of this host. Used to build sslip.io- style generated domains for customer services. Auto-detected via ipify.org/ifconfig.me when omitted; override for NATted or air-gapped hosts. --acme-email Let's Encrypt account contact. Without it, ACME stays off and IC collects it later. --no-docker Skip Docker auto-install on this host. --version Pin the panel image tag (default: latest). Combines with the default repo registry.innovation-lab.co/modern-solutions/licensepanel. --image Pin the FULL panel image reference. Use this when the image lives in a non-default registry or repo (e.g. ghcr.io/dits-sa/licensepanel:1.5.1, localhost:5000/licensepanel:rc, or a Mod-Sol mirror). Overrides --version: the tag is taken from the value after the final colon, the repo from the part before it. The smoke gate (scripts/smoke-install.sh) uses this flag to test release candidates without a local `docker tag` retag dance. --no-start Write all state but do not `docker compose up`. --http-port Edge HTTP port (default 80). With HTTP-01 ACME this must be 80 (Let's Encrypt hardcodes it). With --acme-dns-provider (DNS-01) any free port works. --https-port Edge HTTPS port (default 443). Customer domains reach the panel on standard 443; override only when something else owns 443 (then DNS-01 is required for public TLS, and the upstream proxy/CDN must forward or pass-through to the override port). --panel-port Direct panel-access port (default: 8443, or the next free port if 8443 is in use). --license-server-url Override the LicenseServer BaseUrl. Defaults to https://license-api.mod-sol-sa.com (the production Mod-Sol host). Set to your own host for self-hosted license-server installs. --acme-dns-provider

Use ACME DNS-01 instead of HTTP-01 for Let's Encrypt. No inbound port is needed — the panel proves domain ownership via DNS. Required on hosts where port 80 is taken (Dokploy, existing reverse proxy, ISP block, CDN, firewalled).

is a Lego provider name, e.g. cloudflare | route53 | digitalocean | hetzner | gcloud (full list: https://go-acme.github.io/lego/dns/). Implies --acme-email (the LE account address). --reset WIPE all panel state (state.db, KEK, certs, project data, postgres data volume) before installing fresh. MUST be paired with --yes — there is no interactive confirmation (curl|bash has no tty). --yes Required by --reset to acknowledge the destruction. --acme-dns-env KEY=VAL Provider API credentials, passed as env vars into the Traefik container. Repeat for each variable the provider requires; consult the Lego provider page. Examples: cloudflare: --acme-dns-env CF_DNS_API_TOKEN=... route53: --acme-dns-env AWS_ACCESS_KEY_ID=... --acme-dns-env AWS_SECRET_ACCESS_KEY=... --acme-dns-env AWS_REGION=us-east-1 digitalocean:--acme-dns-env DO_AUTH_TOKEN=... Stored at .env.acme-dns (mode 0600); never echoed. --backend dokploy|compose Orchestration backend. 'compose' (default) runs the self-contained compose edge below; 'dokploy' provisions the panel ON Dokploy (Dokploy owns the edge): installs Docker+pinned Dokploy if absent, seals :3000, then execs bootstrap-dokploy. Requires --registry-* (private image). --air-gapped Force the compose backend (no Dokploy/network install). --expose-dokploy-dashboard Keep Dokploy's :3000 published (default: sealed). --dokploy-api-key Adopt an existing Dokploy (skip admin sign-up). --license DKB-REG: fetch the private-registry pull credential --activation-code from the LicenseServer using the license serial + activation code — the customer types ONLY their license, no registry creds. Requires both. --registry-url Manual override for the license path (or when the --registry-user feature is off): private registry host + pull creds --registry-token for the panel image (both backends). Never echoed. --help Print this help and exit 0. EOF } while [[ $# -gt 0 ]]; do case "$1" in --panel-host) panel_host="$2"; shift 2 ;; --server-ip) server_ip="$2"; shift 2 ;; --acme-email) acme_email="$2"; shift 2 ;; --no-docker) no_docker=1; shift ;; --version) panel_version="$2"; shift 2 ;; --image) # Full repo:tag reference. Split on the LAST colon so the repo can # contain a registry port (localhost:5000/foo:bar → repo=localhost:5000/foo, # tag=bar). Empty tag falls back to whatever --version (or DEFAULT_VERSION) # set; empty repo falls back to DEFAULT_IMAGE_REPO. Reject value that # has neither. _image_full="$2"; shift 2 if [[ -z "$_image_full" ]]; then die "$EXIT_GENERIC" "--image requires a non-empty " fi if [[ "$_image_full" == *:* ]]; then panel_image_repo="${_image_full%:*}" panel_version="${_image_full##*:}" else panel_image_repo="$_image_full" fi ;; --no-start) no_start=1; shift ;; --http-port) http_port="$2"; shift 2 ;; --https-port) https_port="$2"; shift 2 ;; --panel-port) panel_port="$2"; shift 2 ;; --reset) reset=1; shift ;; --yes) yes_flag=1; shift ;; --license-server-url) license_server_base_url="$2"; shift 2 ;; --backend) backend="$2"; shift 2 ;; --air-gapped) air_gapped=1; shift ;; --expose-dokploy-dashboard) expose_dokploy_dashboard=1; shift ;; --dokploy-api-key) dokploy_api_key="$2"; shift 2 ;; --registry-url) registry_url="$2"; shift 2 ;; --registry-user) registry_user="$2"; shift 2 ;; --registry-token) registry_token="$2"; shift 2 ;; --license) license_serial="$2"; shift 2 ;; --activation-code) activation_code="$2"; shift 2 ;; --acme-dns-provider) acme_dns_provider="$2"; shift 2 ;; --acme-dns-env) # Accumulate one KEY=VALUE per occurrence; the array is written to # .env.acme-dns verbatim so Traefik picks them up via env_file. if [[ "$2" != *=* ]]; then echo "error: --acme-dns-env expects KEY=VALUE (got: $2)" >&2 exit "$EXIT_GENERIC" fi acme_dns_env+=("$2"); shift 2 ;; --help) print_help; exit "$EXIT_SUCCESS" ;; *) echo "unknown flag: $1" >&2; print_help; exit "$EXIT_GENERIC" ;; esac done # --- backend selection (plan T16) ------------------------------------------- # `--backend dokploy` provisions the panel ON Dokploy via the shim; `compose` # (default) keeps the self-contained compose edge below. NOTE: the plan's target # default is `dokploy` on Linux (unless --air-gapped); the flip is deferred until # the dokploy path is fully wired + host-tested with the T17 registry login — so # the CURRENT default stays `compose` (existing installs unchanged). `--air-gapped` # always forces compose. if [[ -z "$backend" ]]; then backend="compose" fi if [[ "$air_gapped" -eq 1 ]]; then backend="compose" fi if [[ "$backend" != "dokploy" && "$backend" != "compose" ]]; then echo "error: --backend must be 'dokploy' or 'compose' (got: $backend)" >&2 exit "$EXIT_GENERIC" fi # The dokploy install path runs from main() (dokploy_backend_install), after the # host material (state dirs + KEK + Postgres TLS) is generated. # No required flags. ACME settings without a matching email don't fail the # install — the panel falls back to bootstrap mode (self-signed cert on the # direct-access port) and Initial Configuration collects whatever is missing: # domain, ACME email, challenge type, DNS provider, DNS provider creds. The # warnings here are signal, not a wall — the install always proceeds. # (Direct `echo` rather than the warn() helper because helpers are defined # below the parse block; inlining keeps the validations script-top safe.) if [[ -n "$panel_host" && -z "$acme_email" ]]; then echo "warn: --panel-host was set without --acme-email — ACME will NOT engage yet. The install lands in bootstrap mode (self-signed cert); finish ACME setup in Initial Configuration." >&2 fi if [[ -n "$acme_dns_provider" && -z "$acme_email" ]]; then echo "warn: --acme-dns-provider was set without --acme-email — DNS-01 configured but ACME will NOT engage until an email is set (in Initial Configuration or by re-running with --acme-email)." >&2 fi if [[ -n "$acme_dns_provider" && ${#acme_dns_env[@]} -eq 0 ]]; then echo "warn: --acme-dns-provider was set but no --acme-dns-env credentials were passed. Traefik cannot authenticate to the DNS provider until those are supplied — see https://go-acme.github.io/lego/dns/${acme_dns_provider}/" >&2 fi # ============================================================================ # Helpers # ============================================================================ log() { printf '%s\n' "$*"; } warn() { printf 'warn: %s\n' "$*" >&2; } die() { printf 'error: %s\n' "$2" >&2; exit "$1"; } require_root() { # Sandbox bypass — set PANEL_INSTALL_SANDBOX=1 in the test harness to run # the installer against a temporary $PANEL_INSTALL_ROOT without sudo. This # is NOT honored when no env var is set (real installs always demand root). if [[ "${PANEL_INSTALL_SANDBOX:-0}" == "1" ]]; then return; fi if [[ $EUID -ne 0 ]]; then die "$EXIT_GENERIC" "must run as root (sudo)." fi } # Refuse if state directory exists with wrong permissions (FR-062). preflight_state_perms() { if [[ -d "$PANEL_DIR" ]]; then local mode mode=$(stat -c '%a' "$PANEL_DIR") if [[ "$mode" != "700" && "$mode" != "750" ]]; then die "$EXIT_PERMISSIONS" "$PANEL_DIR exists with mode $mode (expected 700/750). Refusing." fi fi } ensure_state_dirs() { install -d -m 0700 "$PANEL_DIR" "$KEYS_DIR" "$POSTGRES_TLS_DIR" "$TRAEFIK_DIR" "$COMPOSE_DIR" # data/ hosts state.db AND the panel's dataprotection-keys subdir, both # written by the panel container as UID 1654 (chiseled aspnet "app" user). # Owner = 1654, mode 0700 = the panel reads/writes everything; nothing # else on the host (except root) can touch it. Sandbox mode skips the # chown because tests run as a non-root UID without setgid privilege. install -d -m 0700 "$DATA_DIR" if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then chown 1654:1654 "$DATA_DIR" fi # Panel-managed Traefik edge bundle ("Dokploy model" per EdgeProvisioner). # When install.sh's panel-stack Traefik is the source of truth, the panel's # EdgeProvisioner still runs and writes its bundle here at first boot — # its compose-up will fail with "edge degraded" (port conflict) but the # HostedService catches that. The dir itself MUST be writable by UID 1654 # or the panel fatals at line 88 (Directory.CreateDirectory) — that error # path is NOT caught (it happens before the try/catch in EnsureAsync). install -d -m 0700 "$PANEL_DIR/edge" if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then chown 1654:1654 "$PANEL_DIR/edge" fi # Customer-project bundles — ComposeRenderer writes # /var/lib/licensepanel/projects//{docker-compose.yml,.env,mounts/…} # for every deploy. Same UID-1654 rationale as edge/: chiseled image's # /var/lib/ is root-owned, the panel cannot mkdir under it. Bind-mounted # at /var/lib/licensepanel/projects in the panel container (same host path # so the compose path the panel writes resolves on the host when # DockerComposeBackend shells `docker compose -f ` through the # socket-proxy). Without this dir + the matching bind mount, the FIRST # project deploy throws UnauthorizedAccessException at # ComposeRenderer.cs:78 — caught by ProjectCreateWorker as 'Unhandled # deploy fault for operation …' with no clear remediation path. install -d -m 0700 "$PANEL_DIR/projects" if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then # Recursive: projects/ holds only panel-authored bundles (compose, .env, # rendered [[mounts]] config — all 1654). A pre-1.6.2 deploy could leave # ROOT-owned dirs here (Docker auto-creating a missing bind source), which # the nonroot panel can't delete → bricked project. Recursing self-heals # that on reinstall/update. Customer data lives in named volumes (ADR 0028). chown -R 1654:1654 "$PANEL_DIR/projects" fi # One-time migration: earlier installs put state.db directly under # $PANEL_DIR. Move it into data/ so the new path is authoritative and an # operator's upgrade doesn't lose their encrypted state DB. if [[ -f "$PANEL_DIR/state.db" && ! -f "$STATE_DB" ]]; then mv "$PANEL_DIR/state.db" "$STATE_DB" if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then chown 1654:1654 "$STATE_DB" fi log "migrated state.db: $PANEL_DIR/state.db → $STATE_DB" fi } resolve_lib() { local name="$1" if [[ -f "$LIB_DIR_LOCAL/$name" ]]; then echo "$LIB_DIR_LOCAL/$name" return fi # Fetched-from-URL path: stash under the cache dir. `$name` may carry a # `../` segment (e.g. ../panel-stack/docker-compose.yml); strip it for the # cache path so the cached file never resolves onto a real state path # (installer-cache/../panel-stack would BE $COMPOSE_DIR). The URL keeps the # original name — the host normalises /lib/../panel-stack/ to /panel-stack/. # Create the parent before curl — curl never makes parent dirs itself. local dest="$PANEL_DIR/installer-cache/${name//..\//}" if [[ ! -f "$dest" ]]; then install -d -m 0700 "$(dirname "$dest")" curl --fail --silent --show-error --location --retry 3 --retry-delay 2 \ --connect-timeout 10 -o "$dest" "$INSTALLER_LIB_URL/lib/$name" chmod 0700 "$dest" fi echo "$dest" } # ============================================================================ # Port selection (auto-free direct-access port; guarded edge ports) # ============================================================================ # True if anything is listening on the given TCP port. port_in_use() { local p="$1" if command -v ss >/dev/null 2>&1; then ss -Htln "sport = :$p" 2>/dev/null | grep -q . && return 0 || return 1 elif command -v nc >/dev/null 2>&1; then nc -z 127.0.0.1 "$p" >/dev/null 2>&1 else (exec 3<>"/dev/tcp/127.0.0.1/$p") >/dev/null 2>&1 && { exec 3>&-; return 0; } || return 1 fi } # Echo a free port: the preferred one if free, else the next free above it, # else a free high/ephemeral port. find_free_port() { local pref="$1" p if ! port_in_use "$pref"; then echo "$pref"; return; fi for p in $(seq $((pref + 1)) $((pref + 100))); do port_in_use "$p" || { echo "$p"; return; } done for _ in 1 2 3 4 5; do p=$(( (RANDOM % 20000) + 20000 )) port_in_use "$p" || { echo "$p"; return; } done echo "$pref" } # Resolve the three host ports before rendering the compose .env. Edge ports # (80/443) are required for ACME + standard HTTPS, so a conflict is a hard error # with override guidance; the direct-access port auto-frees unless pinned. resolve_ports() { if [[ "$no_docker" -eq 1 ]]; then panel_port="${panel_port:-8443}" # binary shape: nothing binds host ports here http_port="${http_port:-80}" https_port="${https_port:-443}" return fi # Edge ports: empty = "prefer the standard port, auto-fall back if taken" # so bare `curl|bash` works on hosts where 80/443 are already in use # (Dokploy, an existing nginx, a CDN). An explicit override is a pin — # treat a conflict as a hard error so automation gets the deterministic # behaviour it asked for. if [[ -z "$http_port" ]]; then if port_in_use 80; then http_port="$(find_free_port 8080)" log "port 80 is in use; using $http_port for edge HTTP (auto-picked). HTTP-01 ACME won't work on this host — switch to DNS-01 in Initial Configuration." else http_port=80 fi elif port_in_use "$http_port"; then die "$EXIT_PREFLIGHT" "HTTP port $http_port is in use — choose another --http-port or leave it unset to auto-pick." fi if [[ -z "$https_port" ]]; then if port_in_use 443; then https_port="$(find_free_port 8443)" # If panel-port auto-pick later prefers 8443 too, the collision- # avoidance loop below bumps it. Keep https_port distinct from # http_port if they both auto-picked into the 8000s. [[ "$https_port" == "$http_port" ]] && https_port="$(find_free_port $((https_port + 1)))" log "port 443 is in use; using $https_port for edge HTTPS (auto-picked). Customers reaching the panel on standard 443 will need an upstream proxy (see docs §4a)." else https_port=443 fi elif port_in_use "$https_port"; then die "$EXIT_PREFLIGHT" "HTTPS port $https_port is in use — choose another --https-port or leave it unset to auto-pick." fi if [[ -z "$panel_port" ]]; then panel_port="$(find_free_port 8443)" # Auto-pick must avoid colliding with the edge ports the operator chose — # port_in_use checks live listeners only, so at install time neither is # bound yet and find_free_port could pick a number we'll later publish. while [[ "$panel_port" == "$http_port" || "$panel_port" == "$https_port" ]]; do panel_port="$(find_free_port $((panel_port + 1)))" done [[ "$panel_port" != "8443" ]] && log "direct panel-access port: $panel_port (8443 was unavailable or collided with edge ports)." elif port_in_use "$panel_port"; then die "$EXIT_PREFLIGHT" "panel access port $panel_port is in use — choose another --panel-port." elif [[ "$panel_port" == "$http_port" || "$panel_port" == "$https_port" ]]; then die "$EXIT_PREFLIGHT" "--panel-port $panel_port collides with --http-port/--https-port; choose a distinct port." fi # The auto-pick branches above log their own context-specific guidance. # If both edge ports are non-default AND the operator hasn't already set # DNS-01, queue the HTTP-01 nudge — but defer printing until after the # panel reports healthy, so we can check whether EdgeAutoDetect landed # on mode=external (in which case the bundled Traefik is a pass-through # and never issues customer certs, so the tip would be misleading). if [[ "$http_port" != "80" && -z "$acme_dns_provider" ]]; then WARN_HTTP01=1 fi } # ============================================================================ # Installed-already detection (FR-003 / SC-008) # ============================================================================ detect_existing_install() { [[ -f "$STATE_DB" ]] } idempotent_rerun() { log "LicensePanel is already installed." local sha_before sha_before=$(sha256sum "$STATE_DB" | awk '{print $1}') if [[ "$no_docker" -eq 0 ]]; then try_pull_stack_images if [[ "$no_start" -eq 0 ]]; then (cd "$COMPOSE_DIR" && docker compose up -d) \ || die "$EXIT_COMPOSE" "docker compose up reported non-zero." fi fi local sha_after sha_after=$(sha256sum "$STATE_DB" | awk '{print $1}') if [[ "$sha_before" != "$sha_after" ]]; then die "$EXIT_GENERIC" "state.db SHA-256 changed during idempotent re-run (idempotency violation)." fi local svc_state svc_state=$(docker compose -f "$COMPOSE_FILE" ps --format json 2>/dev/null \ | grep -m1 -o '"State":"[^"]*"' | head -1 | cut -d'"' -f4 || echo "unknown") log "Pulled image: ${panel_image_repo}:${panel_version}" log "Service state: ${svc_state:-unknown}" log "Open in your browser:" local bp; bp=$(grep -E '^BOOTSTRAP_PORT=' "$ENV_FILE" 2>/dev/null | cut -d= -f2); bp="${bp:-8443}" if [[ -n "$panel_host" ]]; then log " https://${panel_host}/" fi log " https://$(hostname -I | awk '{print $1}'):${bp}/ (direct access)" exit "$EXIT_SUCCESS" } # ============================================================================ # First-install branches # ============================================================================ install_docker_if_missing() { if [[ "$no_docker" -eq 1 ]]; then log "skipping Docker install (--no-docker)." return fi if command -v docker >/dev/null 2>&1; then return fi log "installing Docker via get.docker.com..." curl -fsSL https://get.docker.com | sh \ || die "$EXIT_DOCKER_INSTALL" "Docker installation failed." } generate_kek_material() { local pfx="$KEYS_DIR/master.pfx" if [[ ! -f "$pfx" ]]; then _generate_kek_pfx "$pfx" fi # Panel container (UID 1654) reads master.pfx via /var/lib/licensepanel/keys # (ro bind mount). Dir at 0751 root:root grants traverse for "other"; # master.pfx at 0600 owned by 1654 lets Kestrel/X509KekProvider read while # the file stays secret from any other host user. Run unconditionally so a # re-run repairs perms from a partial earlier install. Security relies on # this UID-scoped read + the keys/ dir membership, not a PKCS#12 password # the panel would have to read from disk anyway. chmod 0751 "$KEYS_DIR" if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then chown 1654:1654 "$pfx" fi chmod 0600 "$pfx" } # Private — generates the PKCS#12 itself; perm hardening happens above so a # re-run repairs ownership without rewriting the cert (avoids invalidating the # KEK + every encrypted state.db column that derived from it). _generate_kek_pfx() { local pfx="$1" local tmp tmp=$(mktemp -d) openssl req -x509 -nodes -newkey rsa:4096 -days 1825 \ -keyout "$tmp/master.key" -out "$tmp/master.crt" \ -subj "/CN=licensepanel-kek" 2>/dev/null \ || die "$EXIT_TLS" "KEK certificate generation failed." openssl pkcs12 -export \ -out "$pfx" \ -inkey "$tmp/master.key" \ -in "$tmp/master.crt" \ -password pass: \ 2>/dev/null rm -rf "$tmp" chmod 0600 "$pfx" log "kek: master.pfx generated." } generate_postgres_tls() { if [[ ! -f "$POSTGRES_TLS_DIR/server.crt" ]]; then local script script=$(resolve_lib "generate-postgres-tls.sh") bash "$script" "$POSTGRES_TLS_DIR" \ || die "$EXIT_TLS" "Postgres TLS generation failed." fi # Container-consumer setup. Both the postgres:17.x-alpine container # (UID/GID 70) and the panel container (chiseled aspnet, UID 1654) # bind-mount this directory read-only. Each needs: # postgres → traverse the dir + read server.key # panel → traverse the dir + read ca.crt # Directory at 0751 root:root grants traverse to "other" (both UIDs) but # not list. server.key at 0640 root:70 lets the postgres group read while # keeping it secret from the panel (which only needs ca.crt anyway, mode # 0644). This is the alternative permission scheme PostgreSQL officially # documents for system-managed certificate installs (PG17 docs: # "0640 if the file is owned by root … users are added to a specific # group"). Run unconditionally so a re-run repairs stale perms from a # partial earlier install rather than forcing a `rm -rf $PANEL_DIR`. chmod 0751 "$POSTGRES_TLS_DIR" # The chown requires root; skip it in sandbox mode (tests run as the # invoking user, who has no privilege to set arbitrary GIDs). Real # installs always go through require_root before reaching here. if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then chown 0:70 "$POSTGRES_TLS_DIR/server.key" fi chmod 0640 "$POSTGRES_TLS_DIR/server.key" } generate_bootstrap_cert() { if [[ ! -f "$TRAEFIK_DIR/bootstrap-cert.pem" ]]; then local script script=$(resolve_lib "generate-bootstrap-cert.sh") bash "$script" "$TRAEFIK_DIR" \ || die "$EXIT_TLS" "Bootstrap cert generation failed." fi # The bootstrap-cert is consumed by TWO containers via the same host file: # panel-traefik — runs as root (reads anything regardless of mode) # panel — runs as UID 1654 (chiseled aspnet) and uses the cert # for its own Kestrel HTTPS listener (no other cert # ships in the image; without this Kestrel fatals with # "default developer certificate could not be found"). # Dir at 0751 root:root grants traverse to "other" (UID 1654 can enter); # the .key at 0600 owned by 1654 lets Kestrel read it while root can too. # Run unconditionally so a re-run repairs perms from a partial earlier # install. chmod 0751 "$TRAEFIK_DIR" if [[ "${PANEL_INSTALL_SANDBOX:-0}" != "1" ]]; then chown 1654:1654 "$TRAEFIK_DIR/bootstrap-cert.key" fi chmod 0600 "$TRAEFIK_DIR/bootstrap-cert.key" chmod 0644 "$TRAEFIK_DIR/bootstrap-cert.pem" } write_panel_stack() { install -d -m 0750 "$COMPOSE_DIR" # Preserve persistent secrets across re-runs. The Postgres data volume is # init'd with whatever POSTGRES_PASSWORD was set on first boot — that # password is baked into pg_authid. Regenerating .env on every re-run # would silently break auth (cluster has password X, .env now has Y). local postgres_password="" if [[ -f "$ENV_FILE" ]]; then postgres_password=$(awk -F= '/^POSTGRES_PASSWORD=/ {sub(/^[^=]*=/, ""); print; exit}' "$ENV_FILE") fi [[ -z "$postgres_password" ]] && \ postgres_password=$(openssl rand -base64 32 | tr -d '/+=' | head -c 32) # Detect the host's public IP for sslip.io-style generated domains if the # operator didn't supply one via --server-ip. The installer runs directly # on the host (not inside a container), so the external IP is reachable. # Both services are tried in sequence; the `|| true` prevents set -e from # aborting when neither responds (private VMs, strict firewalls). if [ -z "${server_ip}" ]; then server_ip="$(curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null \ || curl -fsS --max-time 5 https://ifconfig.me 2>/dev/null || true)" fi # PANEL_EDGE_PRESET is intentionally left empty here; the panel's # EdgeAutoDetectPolicy fills it at first boot based on host state. cat > "$ENV_FILE" < "$dns_env_file" chmod 0600 "$dns_env_file" local kv for kv in "${acme_dns_env[@]:-}"; do [[ -z "$kv" ]] && continue printf '%s\n' "$kv" >> "$dns_env_file" done local source_overlay source_overlay="$LIB_DIR_LOCAL/../panel-stack/docker-compose.dns01.override.yml" if [[ ! -f "$source_overlay" ]]; then source_overlay=$(resolve_lib "../panel-stack/docker-compose.dns01.override.yml") fi cp "$source_overlay" "$COMPOSE_DIR/docker-compose.override.yml" chmod 0640 "$COMPOSE_DIR/docker-compose.override.yml" log "acme: DNS-01 enabled (provider: $acme_dns_provider) — port 80 is no longer required for cert issuance." fi # Render the compose file from the bundled template. local source_compose="$LIB_DIR_LOCAL/../panel-stack/docker-compose.yml" if [[ ! -f "$source_compose" ]]; then # When running from the curl-piped mode the file lives in the cache. source_compose=$(resolve_lib "../panel-stack/docker-compose.yml") fi cp "$source_compose" "$COMPOSE_FILE" chmod 0640 "$COMPOSE_FILE" # Render Traefik dynamic config directly (template file dropped — its # single-shape substitution couldn't express the two real modes). # ACME mode (panel_host AND acme_email): both routers. The `panel` router # serves the public domain on websecure with certresolver=le; the # bootstrap router stays available for direct-IP access. # Bootstrap mode (anything less): ONLY the bootstrap router. Emitting a # `panel` router with Host("_") + certresolver="bootstrap" (a name that # isn't a real resolver) was the cause of the Traefik startup errors: # - "invalid value for HostSNI matcher, \"_\" is not a valid hostname" # - "Router uses a nonexistent certificate resolver: bootstrap" # Initial Configuration adds the panel router later (or operator re-runs # install.sh with --panel-host + --acme-email). install -d -m 0750 "$TRAEFIK_DIR/dynamic" # Routing rules for both entrypoints (010 Phase 1: keycloak routers # removed; local cookie auth needs no /realms/, /resources/, or /admin/ # path-routing tricks): # # websecure (operator-domain mode, ACME-issued certs): # - panel Host(panel_host) catch-all (only when panel_host+acme_email set) # # bootstrap (direct-IP access, self-signed bootstrap-cert): # - panel-bootstrap catch-all (HTTPS) # - panel-bootstrap-http catch-all (plain HTTP → 302 https, same port) { printf 'http:\n' printf ' routers:\n' if [[ -n "$panel_host" && -n "$acme_email" ]]; then printf ' panel:\n' printf ' rule: "Host(`%s`)"\n' "$panel_host" printf ' entrypoints: [websecure]\n' printf ' priority: 1\n' printf ' service: panel-svc\n' printf ' tls:\n' printf ' certresolver: le\n' fi printf ' panel-bootstrap:\n' printf ' rule: "PathPrefix(`/`)"\n' printf ' entrypoints: [bootstrap]\n' printf ' priority: 1\n' printf ' service: panel-svc\n' printf ' tls: {}\n' # Same bootstrap entrypoint, plain-HTTP twin (no tls). Browsers that # hit http://: — or just type :, which defaults to # http — would otherwise fail the TLS handshake ("you have to use # https"). A tls router ignores non-TLS traffic and a non-tls router # only sees plain HTTP (Traefik routes by connection type), so this one # catches HTTP and 302-redirects to https on the SAME published port. # No loop: the HTTPS request stays on panel-bootstrap (tls). printf ' panel-bootstrap-http:\n' printf ' rule: "PathPrefix(`/`)"\n' printf ' entrypoints: [bootstrap]\n' printf ' priority: 1\n' printf ' service: panel-svc\n' printf ' middlewares: [bootstrap-https-redirect]\n' printf ' middlewares:\n' printf ' bootstrap-https-redirect:\n' printf ' redirectScheme:\n' printf ' scheme: https\n' printf ' port: "%s"\n' "$panel_port" printf ' permanent: false\n' printf ' services:\n' printf ' panel-svc:\n' printf ' loadBalancer:\n' printf ' servers:\n' printf ' - url: "https://panel:8443"\n' printf ' passHostHeader: true\n' printf ' serversTransport: panel-transport\n' printf ' serversTransports:\n' printf ' panel-transport:\n' printf ' insecureSkipVerify: true\n' printf ' forwardingTimeouts:\n' printf ' dialTimeout: "5s"\n' printf ' responseHeaderTimeout: "30s"\n' printf 'tls:\n' printf ' stores:\n' printf ' default:\n' printf ' defaultCertificate:\n' printf ' certFile: "/etc/traefik/bootstrap-cert.pem"\n' printf ' keyFile: "/etc/traefik/bootstrap-cert.key"\n' } > "$TRAEFIK_DIR/dynamic/dynamic.yml" chmod 0640 "$TRAEFIK_DIR/dynamic/dynamic.yml" } # Dump the most useful logs for diagnosing a stuck startup. Called on both # `docker compose up` failure and post-up healthcheck timeout — so the # operator never has to guess which service failed. dump_stack_logs() { warn "recent logs from the stack:" (cd "$COMPOSE_DIR" && docker compose ps 2>&1 | sed 's/^/ /' >&2 || true) (cd "$COMPOSE_DIR" && docker compose logs --tail=40 panel-postgres panel panel-traefik 2>&1 \ | sed 's/^/ /' >&2 || true) warn "full logs: docker compose -f $COMPOSE_FILE logs" } # Always pull the panel + Traefik images from the registry before `compose # up` so a re-run (especially after --reset) picks up the newest published # build. Without this, `docker compose up -d` reuses whatever each tag # (e.g. `panel:latest`) resolved to on the host's *previous* pull — so a # re-install on a host that pulled :latest a week ago would silently boot # last week's panel image even though the registry has a fresher one. # # Pull failures (offline, registry down) are warned about but don't abort: # `compose up` will then start whatever the local cache holds, which is the # correct fallback on air-gapped hosts. # DKB-REG T7 — populate registry_url/user/token/image_prefix. Manual --registry-* # win; otherwise, when --license + --activation-code are given, fetch the # per-license pull credential from the LicenseServer registry-bootstrap endpoint. # No-op when neither is provided (public image / creds out-of-band). resolve_registry_creds() { if [[ -n "$registry_url" && -n "$registry_user" && -n "$registry_token" ]]; then return 0 # manual override present fi if [[ -z "$license_serial" || -z "$activation_code" ]]; then return 0 # nothing to resolve fi # shellcheck source=lib/registry-bootstrap.sh source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/registry-bootstrap.sh" local creds if ! creds=$(registry_bootstrap "$license_server_base_url" "$license_serial" "$activation_code"); then die "$EXIT_GENERIC" "registry-bootstrap failed — check the license serial + activation code." fi registry_url=$(printf '%s\n' "$creds" | sed -n 1p) registry_user=$(printf '%s\n' "$creds" | sed -n 2p) registry_token=$(printf '%s\n' "$creds" | sed -n 3p) registry_image_prefix=$(printf '%s\n' "$creds" | sed -n 4p) log "registry: fetched license-driven pull credential for ${registry_url}" } try_pull_stack_images() { [[ "$no_docker" -eq 1 ]] && return 0 # T17 — the panel image is PRIVATE: log the host in from --registry-* (or the # license-fetched creds) BEFORE the pull. Both are no-ops when absent. resolve_registry_creds # shellcheck source=lib/registry-login.sh source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/registry-login.sh" if ! registry_login "$registry_url" "$registry_user" "$registry_token"; then warn "docker login failed for ${registry_url} — the private panel pull may fail." fi log "pulling stack images (panel, traefik, postgres) ..." if ! (cd "$COMPOSE_DIR" && docker compose pull --quiet); then warn "docker compose pull reported non-zero — falling back to local image cache." fi } bring_stack_up() { [[ "$no_start" -eq 1 ]] && { log "stack not started (--no-start)."; return; } [[ "$no_docker" -eq 1 ]] && { log "stack not started (--no-docker)."; return; } try_pull_stack_images if ! (cd "$COMPOSE_DIR" && docker compose up -d); then dump_stack_logs die "$EXIT_COMPOSE" "docker compose up reported non-zero — see logs above." fi # The panel container has a built-in healthcheck (15s interval, 5 retries, # 30s start_period) — so ~2 minutes of legitimate startup is normal: EF # Core migrations + Wolverine codegen + Kestrel TLS bind. Poll the panel's # health state and only print the success URL once the panel reports # healthy, so the operator's first browser hit isn't a 502 from Traefik # proxying to a not-yet-listening upstream. log "waiting for the panel to report healthy (up to 3 min) ..." log " parallel: docker compose -f $COMPOSE_FILE logs -f panel" local timeout=180 elapsed=0 state="" container_state="" last_beat=0 while [[ "$elapsed" -lt "$timeout" ]]; do # Pull both .State and .Health in one ps call. Without this the loop # would silently poll Health for the full 180s while the container # was actually exiting/restarting on a fatal — exactly the failure # mode the last operator hit (panel restarting on a DataProtection # perms error; we sat at "waiting" until timeout). local ps_line ps_line=$(cd "$COMPOSE_DIR" && docker compose ps --format '{{.Service}} {{.State}} {{.Health}}' 2>/dev/null \ | awk '$1=="panel"{print $2, $3; exit}') container_state="${ps_line%% *}" state="${ps_line##* }" case "$state" in healthy) log "panel is healthy (${elapsed}s)." return ;; unhealthy) dump_stack_logs die "$EXIT_COMPOSE" "panel container reports UNHEALTHY — see logs above." ;; esac case "$container_state" in exited|dead) dump_stack_logs die "$EXIT_COMPOSE" "panel container is ${container_state} mid-boot — see logs above." ;; esac # One progress beat every 15s (matches the healthcheck interval) — the # operator isn't staring at a static "waiting" line for 3 minutes. if (( elapsed - last_beat >= 15 && elapsed > 0 )); then log " still booting (${elapsed}s elapsed, container=${container_state:-?}, health=${state:-starting})" last_beat=$elapsed fi sleep 5 elapsed=$((elapsed + 5)) done warn "panel did not report healthy within ${timeout}s — first boot can be slow on small VMs, but logs may explain why." dump_stack_logs die "$EXIT_COMPOSE" "healthcheck timeout — see logs above. The stack is still running; check again in a minute with: docker compose -f $COMPOSE_FILE ps" } # Emit the deferred HTTP-01 tip queued in resolve_ports, unless the panel's # EdgeAutoDetect concluded the host is in external-edge mode. In external # mode the bundled panel-traefik is a non-routing pass-through — customer # domains get their certs from whatever edge owns 80/443 (Dokploy / Caddy / # nginx), so the "switch to DNS-01" nudge would mislead the operator. # # edge.json is written by EdgeAutoDetectHostedService.StartAsync BEFORE the # panel reports healthy (it runs in StartAsync, and the panel's healthcheck # can only flip to "healthy" once StartAsync completes), so by the time we # get here the file exists on any host where the panel actually came up. # Fallback: if the file can't be read (perms / paths / very old image), keep # the warning suppressed when WARN_HTTP01 was queued — the only reason # WARN_HTTP01 gets set is that an edge auto-pick happened, and an edge # auto-pick happens iff host port 80 is bound, which is exactly the signal # EdgeAutoDetect uses to land on external. So the suppression decision is # the same in both branches. maybe_warn_http01() { [[ "$WARN_HTTP01" -eq 1 ]] || return 0 local edge_json="$DATA_DIR/edge.json" if [[ -r "$edge_json" ]] && grep -q '"Mode"[[:space:]]*:[[:space:]]*"external"' "$edge_json"; then return 0 fi # Fallback: even if edge.json is unreadable, port 80 being bound (which # is what queued WARN_HTTP01 in the first place) means the in-panel # auto-detect will conclude external — suppress to match. Errs toward # "no spurious warning" over "warn that may not apply". if port_in_use 80; then return 0 fi log "tip: with the edge on a non-standard port, the bundled Traefik can't do Let's Encrypt HTTP-01. Set DNS-01 in Initial Configuration or pass --acme-dns-provider on re-run." } print_first_install_summary() { log "" log "LicensePanel installed." log "Open in your browser:" if [[ -n "$panel_host" ]]; then local hsfx=""; [[ "$https_port" != "443" ]] && hsfx=":${https_port}" log " https://${panel_host}${hsfx}/" fi log " https://$(hostname -I | awk '{print $1}'):${panel_port:-8443}/ (direct access)" log "" log "Bootstrap mode is active for the next 60 minutes." log "Stack status: docker compose -f $COMPOSE_FILE ps" log "Stack logs: docker compose -f $COMPOSE_FILE logs -f panel" } # ============================================================================ # Entrypoint # ============================================================================ # --reset --yes: stop the panel-stack (incl. named volumes), wipe the state # dir, and continue with a fresh first-install. Exists so operators don't have # to run a manual `rm -rf` (which is too easy to get wrong and skips the # docker volumes, leaving an orphaned postgres cluster behind). do_reset() { if [[ "$yes_flag" -ne 1 ]]; then die "$EXIT_GENERIC" "--reset will WIPE all panel state (state.db, KEK, certs, project data, postgres data volume). Pair it with --yes to confirm: --reset --yes" fi log "--reset --yes: tearing down stack + wiping $PANEL_DIR ..." if [[ -f "$COMPOSE_FILE" ]] && command -v docker >/dev/null 2>&1; then (cd "$COMPOSE_DIR" && docker compose down --volumes --remove-orphans >/dev/null 2>&1 || true) fi rm -rf "$PANEL_DIR" log "reset complete — proceeding with fresh install." } # Partial-install detection: state dir exists with some material but no # state.db (the install was interrupted before the panel finished first boot). # Resume by reusing whatever is already there — secrets stay stable across # re-runs (see write_panel_stack), so `docker compose up -d` picks up cleanly. log_resume_partial() { [[ -d "$PANEL_DIR" ]] || return 0 local existing=() [[ -f "$KEYS_DIR/master.pfx" ]] && existing+=("KEK") [[ -f "$POSTGRES_TLS_DIR/server.crt" ]] && existing+=("postgres-tls") [[ -f "$TRAEFIK_DIR/bootstrap-cert.pem" ]] && existing+=("bootstrap-cert") [[ -f "$ENV_FILE" ]] && existing+=(".env (secrets)") if [[ ${#existing[@]} -gt 0 ]]; then log "resuming partial install — reusing: ${existing[*]}" fi } # Dokploy backend install (plan T16/T17): ensure Docker + pinned Dokploy + a # sealed :3000 dashboard, log the node into the private registry, then exec the # panel binary's bootstrap-dokploy in a throwaway container on dokploy-network. # Reuses the host material (keys/data/postgres-tls/projects) already generated # by main(). The pull-only compose is registered as the panel's Dokploy app. dokploy_backend_install() { local shim registry_lib pull_compose advertise_addr admin_email admin_password panel_image shim=$(resolve_lib "dokploy-shim.sh") registry_lib=$(resolve_lib "registry-login.sh") pull_compose=$(resolve_lib "../panel-stack/docker-compose.dokploy-pull.yml") # shellcheck disable=SC1090 EXPOSE_DOKPLOY_DASHBOARD="$expose_dokploy_dashboard" source "$shim" # shellcheck disable=SC1090 source "$registry_lib" advertise_addr="${server_ip:-$(hostname -I 2>/dev/null | awk '{print $1}')}" dokploy_install_docker_if_absent dokploy_install_if_absent "$advertise_addr" dokploy_seal_dashboard # DKB-REG T7 — resolve the registry credential (manual --registry-* or the # license serial + activation code) so the swarm node can pull the private # panel image and bootstrap-dokploy can register it with Dokploy. resolve_registry_creds registry_login "$registry_url" "$registry_user" "$registry_token" \ || warn "docker login failed for ${registry_url} — the private panel pull may fail." panel_image="${panel_image_repo}:${panel_version}" admin_email="admin@${panel_host:-localhost}" admin_password="$(openssl rand -base64 24 2>/dev/null || head -c 18 /dev/urandom | base64)" local domain_args=() adopt_args=() [[ -n "$panel_host" ]] && domain_args=(--panel-domain "$panel_host") [[ -n "$dokploy_api_key" ]] && adopt_args=(--dokploy-api-key "$dokploy_api_key") # Ephemeral container on dokploy-network reaches http://dokploy:3000/. The # pull-only compose is bind-mounted as --panel-compose-file. Secrets pass as # args to a throwaway root-only container; the panel persists them to # KeyCustody and never echoes them. if ! docker run --rm --pull always --network dokploy-network \ -e Panel__State__SqlitePath=/tmp/state.db \ -v "${pull_compose}:/tmp/panel-compose.yml:ro" \ "$panel_image" server bootstrap-dokploy \ --dokploy-url "http://dokploy:3000/" \ --admin-email "$admin_email" \ --admin-password "$admin_password" \ --registry-url "$registry_url" \ --registry-user "$registry_user" \ --registry-token "$registry_token" \ --image-prefix "$registry_image_prefix" \ --panel-project "licensepanel" \ --panel-compose-file "/tmp/panel-compose.yml" \ "${domain_args[@]}" "${adopt_args[@]}"; then die "$EXIT_GENERIC" "bootstrap-dokploy failed." fi log "dokploy backend: panel provisioned on Dokploy." [[ -n "$panel_host" ]] && log " https://${panel_host}/" } main() { require_root # --reset runs BEFORE the perms preflight: the whole point of --reset is # to recover from any prior state, including a state dir with wrong perms. if [[ "$reset" -eq 1 ]]; then do_reset fi preflight_state_perms if detect_existing_install; then idempotent_rerun fi log_resume_partial ensure_state_dirs resolve_ports install_docker_if_missing generate_kek_material generate_postgres_tls generate_bootstrap_cert # Dokploy backend: provision on Dokploy and finish (skip the compose edge). if [[ "$backend" == "dokploy" ]]; then dokploy_backend_install return fi write_panel_stack bring_stack_up maybe_warn_http01 print_first_install_summary } main "$@"