#!/usr/bin/env sh
# ldcmd — Limedoc pack developer command bridge (generic / installable)
#
# Usage: ldcmd <command> [args…]
# Install: see install.sh / README.md
# Config: process env → .env.ldcmd → cwd heuristics → interactive prompt

set -e

LDCMD_VERSION="0.1.0"
# Prefer VERSION next to this script when present (dev checkout / zip layout).
_ldcmd_home="$(CDPATH= cd -- "$(dirname "$0")" 2>/dev/null && pwd)"
if [ -f "${_ldcmd_home}/VERSION" ]; then
	LDCMD_VERSION="$(tr -d '[:space:]' < "${_ldcmd_home}/VERSION")"
elif [ -f "${_ldcmd_home}/ldcmd.VERSION" ]; then
	LDCMD_VERSION="$(tr -d '[:space:]' < "${_ldcmd_home}/ldcmd.VERSION")"
fi

COMPOSE_FILE="compose.dev.yml"
# Helper image for volume copies (ldcmd data …). Set a digest reference
# (alpine@sha256:…) to pin it.
LDCMD_HELPER_IMAGE="${LDCMD_HELPER_IMAGE:-alpine:3.20}"
APP_SERVICE="app-dev"
ENV_LDCMD=".env.ldcmd"
DEFAULT_PACKAGE_REGISTRY_URL="https://git.belowtoxic.cloud"

# ── helpers ───────────────────────────────────────────────────────────────────

die() { echo "ldcmd: $*" >&2; exit 1; }

info() { echo "ldcmd: $*" >&2; }

# ── progress (tell a slow step from a hang) ──────────────────────────────────

# Seconds since the epoch (0 without date: progress times then read 0s).
now_secs() {
	date +%s 2>/dev/null || echo 0
}

LDCMD_T0="$(now_secs)"
LDCMD_HEARTBEAT_SECS="${LDCMD_HEARTBEAT_SECS:-15}"

# A major step, with the time since ldcmd started.
step() {
	info "==> $* (+$(($(now_secs) - LDCMD_T0))s)"
}

# run_long <label> <command…>: run an external command and, every
# LDCMD_HEARTBEAT_SECS while it runs, say that it is still running; then
# report how long it took. Returns the command's status.
run_long() {
	_rl_label="$1"
	shift
	_rl_t0="$(now_secs)"
	"$@" &
	_rl_pid=$!
	(
		while :; do
			sleep "${LDCMD_HEARTBEAT_SECS}" </dev/null >/dev/null 2>&1
			kill -0 "${_rl_pid}" 2>/dev/null || exit 0
			info "    … ${_rl_label}: still running ($(($(now_secs) - _rl_t0))s)"
		done
	) &
	_rl_hb=$!
	_rl_st=0
	wait "${_rl_pid}" || _rl_st=$?
	kill "${_rl_hb}" 2>/dev/null || true
	wait "${_rl_hb}" 2>/dev/null || true
	_rl_d=$(($(now_secs) - _rl_t0))
	if [ "${_rl_st}" -eq 0 ]; then
		info "    ${_rl_label}: done (${_rl_d}s)"
	else
		info "    ${_rl_label}: failed after ${_rl_d}s (exit ${_rl_st})"
	fi
	return "${_rl_st}"
}

is_tty() { [ -t 0 ] && [ -t 1 ]; }

prompt_val() {
	# prompt_val <var> <message> [default]
	_pv_var="$1"
	_pv_msg="$2"
	_pv_def="$3"
	if [ -n "${_pv_def}" ]; then
		printf "%s [%s]: " "${_pv_msg}" "${_pv_def}" >&2
	else
		printf "%s: " "${_pv_msg}" >&2
	fi
	if ! is_tty; then
		die "non-interactive: ${_pv_msg} not set (set in .env.ldcmd or env)"
	fi
	_pv_val=""
	read -r _pv_val || true
	[ -z "${_pv_val}" ] && _pv_val="${_pv_def}"
	# The answer is assigned by reference, never parsed as shell text.
	case "${_pv_var}" in
		""|[!A-Za-z_]*|*[!A-Za-z0-9_]*) die "prompt_val: invalid variable name" ;;
	esac
	eval "${_pv_var}=\${_pv_val}"
}

# Compose arguments are built as words (${COMPOSE_ARGS}): a path with
# whitespace or shell pattern characters would be split or expanded.
require_plain_path() {
	case "$2" in
		*" "*|*"	"*|*"
"*|*"*"*|*"?"*|*"["*)
			die "$1 '$2' contains whitespace or one of * ? [ — ldcmd cannot pass it to docker compose; use a path without them" ;;
	esac
}

# ── downloads ────────────────────────────────────────────────────────────────
#
# Registry downloads use HTTPS only (TLS 1.2+, redirects included), a time
# limit and a size limit. A local mirror over plain HTTP needs
# LDCMD_ALLOW_INSECURE_URL=1 (as install.sh).
LDCMD_DL_MAX_TIME="${LDCMD_DL_MAX_TIME:-900}"
# Checksums, signatures, API answers.
LDCMD_META_MAX_BYTES=1048576
# Deploy bundle and ldcmd release zips, and what they may unpack to.
LDCMD_BUNDLE_MAX_BYTES="${LDCMD_BUNDLE_MAX_BYTES:-33554432}"
LDCMD_BUNDLE_MAX_EXTRACT_BYTES="${LDCMD_BUNDLE_MAX_EXTRACT_BYTES:-134217728}"
# Sidecar pack zips, and what they may unpack to.
LDCMD_PACK_MAX_BYTES="${LDCMD_PACK_MAX_BYTES:-268435456}"
LDCMD_PACK_MAX_EXTRACT_BYTES="${LDCMD_PACK_MAX_EXTRACT_BYTES:-1073741824}"
LDCMD_ZIP_MAX_ENTRIES="${LDCMD_ZIP_MAX_ENTRIES:-20000}"

# ld_curl <max bytes> <curl args…>
ld_curl() {
	_lc_max="$1"
	shift
	if [ "${LDCMD_ALLOW_INSECURE_URL:-}" != "1" ]; then
		set -- --proto '=https' --proto-redir '=https' --tlsv1.2 "$@"
	fi
	curl --connect-timeout 20 --max-time "${LDCMD_DL_MAX_TIME}" \
		--max-filesize "${_lc_max}" "$@"
}

# ld_download <max bytes> <url> <out>: fetch (fails on HTTP errors); the size
# is checked again on disk (curl cannot enforce it without Content-Length on
# older versions).
ld_download() {
	ld_curl "$1" -fsSL "$2" -o "$3" || return 1
	_ld_size="$(wc -c < "$3" | tr -d ' ')"
	if [ "${_ld_size}" -gt "$1" ]; then
		rm -f "$3"
		info "download of $(basename "$3") exceeds $1 bytes"
		return 1
	fi
}

# safe_unzip <zip> <dest dir> <max bytes> [unzip options…]
# Extracts with a quota: the declared total and the entry count are checked
# first, no single file may grow beyond the quota while it is written
# (ulimit -f), and the extracted tree is measured afterwards. Returns 1
# (dest may hold a partial tree) when the archive is refused.
safe_unzip() {
	_sz_zip="$1"
	_sz_dest="$2"
	_sz_max="$3"
	shift 3
	_sz_tot="$(unzip -l "${_sz_zip}" 2>/dev/null | tail -1)" || return 1
	_sz_bytes="$(printf '%s\n' "${_sz_tot}" | awk '{print $1}')"
	_sz_count="$(printf '%s\n' "${_sz_tot}" | awk '{print $2}')"
	case "${_sz_bytes}" in
		""|*[!0-9]*) info "cannot read the content list of $(basename "${_sz_zip}")"; return 1 ;;
	esac
	case "${_sz_count}" in
		""|*[!0-9]*) info "cannot read the content list of $(basename "${_sz_zip}")"; return 1 ;;
	esac
	if [ "${_sz_bytes}" -gt "${_sz_max}" ]; then
		info "$(basename "${_sz_zip}") would unpack to ${_sz_bytes} bytes (limit ${_sz_max})"
		return 1
	fi
	if [ "${_sz_count}" -gt "${LDCMD_ZIP_MAX_ENTRIES}" ]; then
		info "$(basename "${_sz_zip}") holds ${_sz_count} entries (limit ${LDCMD_ZIP_MAX_ENTRIES})"
		return 1
	fi
	mkdir -p "${_sz_dest}" || return 1
	(
		# 512-byte blocks; shells without the limit extract without it.
		ulimit -f "$(((_sz_max + 511) / 512))" 2>/dev/null || true
		unzip "$@" "${_sz_zip}" -d "${_sz_dest}"
	) || return 1
	_sz_kb="$(du -sk "${_sz_dest}" 2>/dev/null | awk '{print $1}')"
	case "${_sz_kb}" in
		""|*[!0-9]*) return 0 ;;
	esac
	if [ "${_sz_kb}" -gt "$(((_sz_max / 1024) + 1024))" ]; then
		info "$(basename "${_sz_zip}") unpacked to ${_sz_kb} KiB on disk (limit ${_sz_max} bytes)"
		return 1
	fi
}

# Resolve previous deploy env path relative to BOOTSTRAP_CWD (invocation dir).
# Accepts absolute paths, ~/…, ./name, or bare name (any filename).
resolve_prev_env_path() {
	_raw="$1"
	[ -n "${_raw}" ] || return 1
	_cwd="${BOOTSTRAP_CWD:-$(pwd)}"
	case "${_raw}" in
		~/*) _raw="${HOME}/${_raw#~/}" ;;
	esac
	case "${_raw}" in
		/*) printf '%s\n' "${_raw}" ;;
		./*) printf '%s\n' "${_cwd}/${_raw#./}" ;;
		*) printf '%s\n' "${_cwd}/${_raw}" ;;
	esac
}

json_field() {
	# json_field <file> <key> — naive JSON string field extract
	_jf_file="$1"
	_jf_key="$2"
	[ -f "${_jf_file}" ] || return 1
	grep -E "\"${_jf_key}\"[[:space:]]*:" "${_jf_file}" 2>/dev/null |
		head -1 |
		sed 's/.*"'"${_jf_key}"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' |
		grep -v '^$' || return 1
}

owner_for_kind() {
	case "$1" in
		plugin) echo "limedoc-plugins" ;;
		skin) echo "limedoc-skins" ;;
		template) echo "limedoc-templates" ;;
		*) return 1 ;;
	esac
}

pack_dir_for() {
	_kind="$1"
	_id="$2"
	case "${_kind}" in
		plugin) echo "/limedoc/plugins/${_id}.plugin" ;;
		skin) echo "/limedoc/skins/${_id}" ;;
		template) echo "/limedoc/templates/${_id}" ;;
		*) return 1 ;;
	esac
}

pack_task_for() {
	case "$1" in
		plugin) echo "plugin:pack" ;;
		skin) echo "skin:pack" ;;
		template) echo "template:pack" ;;
		*) return 1 ;;
	esac
}

validate_config() {
	_ok=0
	case "${PACK_KIND}" in
		plugin|skin|template) ;;
		*)
			info "invalid PACK_KIND '${PACK_KIND}'"
			_ok=1
			;;
	esac
	[ -n "${PACK_ID}" ] || {
		info "PACK_ID is empty"
		_ok=1
	}
	[ -f "${COMPOSE_FILE}" ] || {
		info "missing ${COMPOSE_FILE} in cwd"
		_ok=1
	}
	if [ "${PACK_KIND}" = "plugin" ] && [ -n "${PACK_ID}" ]; then
		if [ ! -f "${PACK_ID}.plugin.json" ] && [ ! -f "limedoc.project.json" ]; then
			info "expected ${PACK_ID}.plugin.json or limedoc.project.json"
			_ok=1
		fi
	fi
	[ -n "${PACK_DIR}" ] || {
		info "PACK_DIR is empty"
		_ok=1
	}
	[ -n "${PACK_TASK}" ] || {
		info "PACK_TASK is empty"
		_ok=1
	}
	[ -n "${PACKAGE_OWNER_DEFAULT}" ] || {
		info "PACKAGE_OWNER_DEFAULT is empty"
		_ok=1
	}
	return "${_ok}"
}

detect_from_cwd() {
	_d_kind=""
	_d_id=""
	_d_dir=""
	_d_task=""
	_d_owner=""

	if [ -f "limedoc.project.json" ]; then
		_d_kind="$(json_field limedoc.project.json kind || true)"
		_d_id="$(json_field limedoc.project.json id || true)"
	fi

	if [ -z "${_d_id}" ]; then
		for _mf in *.plugin.json; do
			[ -f "${_mf}" ] || continue
			_d_id="$(json_field "${_mf}" id || true)"
			[ -n "${_d_id}" ] && _d_kind="plugin"
			break
		done
	fi

	# Heuristic: skin / template packs without limedoc.project.json
	if [ -z "${_d_kind}" ]; then
		_base="$(basename "$(pwd)")"
		if [ -f "manifest.json" ] && grep -q '"layers"' manifest.json 2>/dev/null; then
			_d_kind="skin"
			_d_id="${_base}"
		elif [ -f "metadata.json" ] && { [ -d "domains" ] || [ -d "include" ]; }; then
			_d_kind="template"
			_d_id="${_base}"
		fi
	fi

	if [ -n "${_d_kind}" ] && [ -n "${_d_id}" ]; then
		_d_dir="$(pack_dir_for "${_d_kind}" "${_d_id}" || true)"
		_d_task="$(pack_task_for "${_d_kind}" || true)"
		_d_owner="$(owner_for_kind "${_d_kind}" || true)"
	fi

	DETECTED_KIND="${_d_kind}"
	DETECTED_ID="${_d_id}"
	DETECTED_DIR="${_d_dir}"
	DETECTED_TASK="${_d_task}"
	DETECTED_OWNER="${_d_owner}"
}

write_env_ldcmd() {
	cat > "${ENV_LDCMD}" << EOF
# Generated by ldcmd ${LDCMD_VERSION} — safe to edit; re-run: ldcmd init
PACK_KIND=${PACK_KIND}
PACK_ID=${PACK_ID}
PACK_DIR=${PACK_DIR}
PACK_TASK=${PACK_TASK}
PACKAGE_OWNER_DEFAULT=${PACKAGE_OWNER_DEFAULT}
PACKAGE_REGISTRY_URL=${PACKAGE_REGISTRY_URL:-${DEFAULT_PACKAGE_REGISTRY_URL}}
EOF
	info "wrote ${ENV_LDCMD}"
}

load_env_files() {
	if [ -f ".env" ]; then
		# shellcheck disable=SC1091
		set -a
		. "./.env"
		set +a
	fi
	if [ -f "${ENV_LDCMD}" ]; then
		# shellcheck disable=SC1091
		set -a
		. "./${ENV_LDCMD}"
		set +a
	fi
	# Canonical names; accept legacy FORGEJO_* aliases when unset
	PACKAGE_OWNER_DEFAULT="${PACKAGE_OWNER_DEFAULT:-${FORGEJO_OWNER_DEFAULT:-}}"
	PACKAGE_REGISTRY_URL="${PACKAGE_REGISTRY_URL:-${FORGEJO_BASE_URL:-}}"
	PACKAGE_OWNER="${PACKAGE_OWNER:-${FORGEJO_OWNER:-}}"
	PACKAGE_TOKEN="${PACKAGE_TOKEN:-${FORGEJO_TOKEN:-}}"
}

resolve_config() {
	_force_init="${1:-}"

	load_env_files

	# Snapshot env overrides (highest priority after explicit force-init ask)
	_env_kind="${PACK_KIND:-}"
	_env_id="${PACK_ID:-}"
	_env_dir="${PACK_DIR:-}"
	_env_task="${PACK_TASK:-}"
	_env_owner="${PACKAGE_OWNER_DEFAULT:-}"
	_env_base="${PACKAGE_REGISTRY_URL:-}"

	if [ "${_force_init}" = "init" ] || [ ! -f "${ENV_LDCMD}" ]; then
		detect_from_cwd
		PACK_KIND="${_env_kind:-${DETECTED_KIND:-}}"
		PACK_ID="${_env_id:-${DETECTED_ID:-}}"
		PACK_DIR="${_env_dir:-${DETECTED_DIR:-}}"
		PACK_TASK="${_env_task:-${DETECTED_TASK:-}}"
		PACKAGE_OWNER_DEFAULT="${_env_owner:-${DETECTED_OWNER:-}}"
		PACKAGE_REGISTRY_URL="${_env_base:-}"

		if ! validate_config; then
			info "could not fully detect pack config — prompting"
			[ -n "${PACK_KIND}" ] ||
				prompt_val PACK_KIND "Pack kind (plugin|skin|template)" "plugin"
			[ -n "${PACK_ID}" ] || prompt_val PACK_ID "Pack id" "${PACK_ID}"

			# Derived fields — never prompt (env override already applied above)
			[ -n "${PACK_DIR}" ] ||
				PACK_DIR="$(pack_dir_for "${PACK_KIND}" "${PACK_ID}")"
			[ -n "${PACK_TASK}" ] || PACK_TASK="$(pack_task_for "${PACK_KIND}")"

			# Registry: main Limedoc defaults vs custom URL/owner
			if [ -z "${_env_base}" ]; then
				_reg_mode="main"
				if is_tty; then
					prompt_val _reg_mode \
						"Package registry (main|custom)" "main"
				fi
				case "${_reg_mode}" in
					custom|c|Custom|CUSTOM)
						prompt_val PACKAGE_REGISTRY_URL \
							"Package registry base URL" \
							"${DEFAULT_PACKAGE_REGISTRY_URL}"
						_sug_owner="$(owner_for_kind "${PACK_KIND}" 2>/dev/null || true)"
						prompt_val PACKAGE_OWNER_DEFAULT \
							"Package registry owner" \
							"${PACKAGE_OWNER_DEFAULT:-${_sug_owner}}"
						;;
					*)
						PACKAGE_REGISTRY_URL="${DEFAULT_PACKAGE_REGISTRY_URL}"
						PACKAGE_OWNER_DEFAULT="$(owner_for_kind "${PACK_KIND}")"
						;;
				esac
			else
				PACKAGE_REGISTRY_URL="${_env_base}"
				[ -n "${PACKAGE_OWNER_DEFAULT}" ] ||
					PACKAGE_OWNER_DEFAULT="$(owner_for_kind "${PACK_KIND}")"
			fi
		fi

		# Fill any remaining derived fields
		[ -n "${PACK_DIR}" ] ||
			PACK_DIR="$(pack_dir_for "${PACK_KIND}" "${PACK_ID}")"
		[ -n "${PACK_TASK}" ] || PACK_TASK="$(pack_task_for "${PACK_KIND}")"
		[ -n "${PACKAGE_OWNER_DEFAULT}" ] ||
			PACKAGE_OWNER_DEFAULT="$(owner_for_kind "${PACK_KIND}")"
		[ -n "${PACKAGE_REGISTRY_URL}" ] ||
			PACKAGE_REGISTRY_URL="${DEFAULT_PACKAGE_REGISTRY_URL}"

		if ! validate_config; then
			die "config invalid after prompts; fix .env.ldcmd or re-run ldcmd init"
		fi
		write_env_ldcmd
	else
		# Loaded from .env.ldcmd / env — fill gaps from detection if needed
		if [ -z "${PACK_KIND}" ] || [ -z "${PACK_ID}" ] ||
			[ -z "${PACK_DIR}" ] || [ -z "${PACK_TASK}" ] ||
			[ -z "${PACKAGE_OWNER_DEFAULT}" ]; then
			detect_from_cwd
			PACK_KIND="${PACK_KIND:-${DETECTED_KIND}}"
			PACK_ID="${PACK_ID:-${DETECTED_ID}}"
			PACK_DIR="${PACK_DIR:-${DETECTED_DIR}}"
			PACK_TASK="${PACK_TASK:-${DETECTED_TASK}}"
			PACKAGE_OWNER_DEFAULT="${PACKAGE_OWNER_DEFAULT:-${DETECTED_OWNER}}"
		fi
		PACKAGE_REGISTRY_URL="${PACKAGE_REGISTRY_URL:-${DEFAULT_PACKAGE_REGISTRY_URL}}"
		if ! validate_config; then
			info "saved config failed validation — re-init"
			resolve_config init
			return
		fi
	fi
}

setup_compose() {
	DOCKER="${DOCKER_CMD:-docker}" # set DOCKER_CMD=podman for rootless
	if "${DOCKER}" compose version >/dev/null 2>&1; then
		COMPOSE="${DOCKER} compose"
	elif command -v "${DOCKER}-compose" >/dev/null 2>&1; then
		COMPOSE="${DOCKER}-compose"
	else
		die "neither '${DOCKER} compose' nor '${DOCKER}-compose' found"
	fi
	COMPOSE_CMD="${COMPOSE} -f ${COMPOSE_FILE}"
	: "${APP_SERVICE:=app-dev}"
}

require_up() {
	if ! ${COMPOSE_CMD} ps --quiet "${APP_SERVICE}" 2>/dev/null | grep -q .; then
		die "${APP_SERVICE} container is not running. Start it first with: ldcmd up"
	fi
}

exec_in_app() {
	# shellcheck disable=SC2086
	${COMPOSE_CMD} exec ${EXEC_IN_APP_FLAGS:-} "${APP_SERVICE}" "$@"
}

# Resolve compose + app service for runtime pack ops (install/ls).
# Pack-dev: compose.dev.yml + app-dev. Prod: deploy dir + app.
# Does NOT require .env.ldcmd / pack identity.
resolve_runtime_app_exec() {
	if prod_context; then
		resolve_prod_deploy_dir
		prod_core_compose_args
		DOCKER="${DOCKER_CMD:-docker}"
		if "${DOCKER}" compose version >/dev/null 2>&1; then
			COMPOSE="${DOCKER} compose"
		elif command -v "${DOCKER}-compose" >/dev/null 2>&1; then
			COMPOSE="${DOCKER}-compose"
		else
			die "neither '${DOCKER} compose' nor '${DOCKER}-compose' found"
		fi
		# shellcheck disable=SC2086
		COMPOSE_CMD="${COMPOSE} ${COMPOSE_ARGS} ${PROFILE_ARGS}"
		APP_SERVICE="app"
		APP_ROOT_IN_CONTAINER="/app"
		EXEC_IN_APP_FLAGS="-T"
		RUNTIME_CONTEXT="prod"
	elif [ -f "${COMPOSE_FILE}" ]; then
		setup_compose
		APP_SERVICE="app-dev"
		APP_ROOT_IN_CONTAINER="/limedoc"
		EXEC_IN_APP_FLAGS="-T"
		RUNTIME_CONTEXT="pack-dev"
	else
		die "plugin/skin/template: this pack checkout has no ${COMPOSE_FILE}; for an instance: ldcmd -i <id> ${_kind:-plugin} …"
	fi
}

# Runtime pack ops: ldcmd {plugin|skin|template} {install|ls|uninstall|…}
cmd_pack_kind_ops() {
	_kind="$1"
	shift
	_sub="${1:-}"
	shift || true
	case "${_kind}" in
		plugin|skin|template) ;;
		*) die "internal: invalid pack kind '${_kind}'" ;;
	esac

	# skin select/palette need runtime exec too
	case "${_sub}" in
		deactivate|activate)
			if [ "${_kind}" = "skin" ]; then
				die "skin: use 'ldcmd skin select' / 'ldcmd skin palette' (skins are not deactivated)"
			fi
			;;
	esac

	case "${_sub}" in
		install|uninstall|update|ls|activate|deactivate|select|palette) ;;
		*)
			help_text "${_kind}" >&2
			die "${_kind}: unknown sub-command '${_sub}' (install|uninstall|update|ls|activate|deactivate|select|palette)"
			;;
	esac
	resolve_runtime_app_exec
	case "${_sub}" in
		install)
			force_flag=
			with_deps_flag=
			while [ $# -gt 0 ]; do
				case "$1" in
					--force) force_flag=--force; shift ;;
					--with-deps) with_deps_flag=--with-deps; shift ;;
					-*) die "${_kind} install: unknown flag $1" ;;
					*) break ;;
				esac
			done
			_id="${1:?usage: ldcmd ${_kind} install [--force] [--with-deps] <id>}"
			require_up
			case "${_kind}" in
				plugin) _spec="${_id}" ;;
				*) _spec="${_kind}:${_id}" ;;
			esac
			_st=0
			# shellcheck disable=SC2086
			_out="$(exec_in_app deno run --allow-env --allow-read --allow-write \
				--allow-net --allow-run=unzip \
				"${APP_ROOT_IN_CONTAINER}/scripts/packs_install.ts" \
				${force_flag} ${with_deps_flag} "${_spec}")" || _st=$?
			printf '%s\n' "${_out}" | grep -v '^LIMEDOC_' || true
			[ "${_st}" -eq 0 ] || return "${_st}"
			printf '%s\n' "${_out}" | sed -n 's/^LIMEDOC_SIDECAR_UP=//p' |
				while IFS= read -r _sid; do
					[ -n "${_sid}" ] || continue
					info "pack declares sidecar: ldcmd sidecar up ${_sid} --configure (prod deploy dir)"
				done
			if printf '%s\n' "${_out}" | grep -q '^LIMEDOC_SIDECAR_UP='; then
				info "finish with: ldcmd up  (recreate app so pack install .env / mounts apply)"
			fi
			app_restart_followup "${_out}" 0
			;;
		uninstall)
			force_flag=
			while [ $# -gt 0 ]; do
				case "$1" in
					--force) force_flag=--force; shift ;;
					-*) die "${_kind} uninstall: unknown flag $1" ;;
					*) break ;;
				esac
			done
			_id="${1:?usage: ldcmd ${_kind} uninstall [--force] <id>}"
			require_up
			case "${_kind}" in
				plugin) _spec="${_id}" ;;
				*) _spec="${_kind}:${_id}" ;;
			esac
			_st=0
			# shellcheck disable=SC2086
			_out="$(exec_in_app deno run --allow-env --allow-read --allow-write \
				--allow-net \
				"${APP_ROOT_IN_CONTAINER}/scripts/packs_uninstall.ts" \
				${force_flag} "${_spec}")" || _st=$?
			printf '%s\n' "${_out}" | grep -v '^LIMEDOC_' || true
			[ "${_st}" -eq 0 ] || return "${_st}"
			if [ "${RUNTIME_CONTEXT}" = "prod" ]; then
				printf '%s\n' "${_out}" | sed -n 's/^LIMEDOC_SIDECAR_DOWN=//p' |
					while IFS= read -r _sid; do
						[ -n "${_sid}" ] || continue
						info "stopping sidecar for ${_sid}"
						cmd_sidecar_down "${_sid}" || true
					done
			fi
			;;
		ls)
			_installed=
			while [ $# -gt 0 ]; do
				case "$1" in
					--installed) _installed=--installed; shift ;;
					-*) die "${_kind} ls: unknown flag $1" ;;
					*) break ;;
				esac
			done
			require_up
			# shellcheck disable=SC2086
			exec_in_app deno run --allow-env --allow-read --allow-net \
				"${APP_ROOT_IN_CONTAINER}/scripts/packs_browse.ts" \
				--kind "${_kind}" ${_installed}
			;;
		deactivate)
			_id="${1:?usage: ldcmd ${_kind} deactivate <id>}"
			require_up
			if [ "${_kind}" = "plugin" ]; then
				# --allow-net: Redis lock + reload broadcast to the running app.
				exec_in_app deno run --allow-env --allow-read --allow-write \
					--allow-net \
					"${APP_ROOT_IN_CONTAINER}/scripts/plugins_set_enabled.ts" \
					"${_id}" false
			else
				exec_in_app deno run --allow-env --allow-read --allow-write \
					"${APP_ROOT_IN_CONTAINER}/scripts/templates_set_enabled.ts" \
					"${_id}" false
			fi
			;;
		activate)
			_id="${1:?usage: ldcmd ${_kind} activate <id>}"
			require_up
			if [ "${_kind}" = "plugin" ]; then
				# --allow-net: Redis lock + reload broadcast to the running app.
				exec_in_app deno run --allow-env --allow-read --allow-write \
					--allow-net \
					"${APP_ROOT_IN_CONTAINER}/scripts/plugins_set_enabled.ts" \
					"${_id}" true
			else
				exec_in_app deno run --allow-env --allow-read --allow-write \
					"${APP_ROOT_IN_CONTAINER}/scripts/templates_set_enabled.ts" \
					"${_id}" true
			fi
			;;
		select)
			[ "${_kind}" = "skin" ] ||
				die "${_kind}: unknown sub-command 'select'"
			_id="${1:?usage: ldcmd skin select <fullSkinId>}"
			require_up
			exec_in_app deno run --allow-env --allow-read --allow-write \
				"${APP_ROOT_IN_CONTAINER}/scripts/skins_set_active.ts" \
				--core "${_id}"
			;;
		palette)
			[ "${_kind}" = "skin" ] ||
				die "${_kind}: unknown sub-command 'palette'"
			_id="${1:?usage: ldcmd skin palette <palettePackId>|none}"
			require_up
			exec_in_app deno run --allow-env --allow-read --allow-write \
				"${APP_ROOT_IN_CONTAINER}/scripts/skins_set_active.ts" \
				--palette "${_id}"
			;;
		update)
			_check=
			_no_restart=0
			while [ $# -gt 0 ]; do
				case "$1" in
					--check|--dry-run) _check=--check; shift ;;
					--no-restart) _no_restart=1; shift ;;
					-*) die "${_kind} update: unknown flag $1" ;;
					*) break ;;
				esac
			done
			for _id in "$@"; do
				case "${_id}" in
					''|*[!a-z0-9-]*) die "${_kind} update: invalid pack id '${_id}'" ;;
				esac
			done
			require_up
			_st=0
			run_packs_update ${_check} --kind "${_kind}" "$@" || _st=$?
			pack_update_followups "${_no_restart}"
			return "${_st:-0}"
			;;
		*)
			help_text "${_kind}" >&2
			die "${_kind}: unknown sub-command '${_sub}' (install|uninstall|update|ls|activate|deactivate|select|palette)"
			;;
	esac
}

# run_packs_update [args…] — scripts/packs_update.ts in the running app.
# Prints the human lines; the LIMEDOC_* markers stay in PACKS_UPDATE_OUT.
run_packs_update() {
	app_has_packs_update ||
		die "this app image has no packs:update yet; update the instance first: ldcmd update"
	_pu_st=0
	_pu_out="$(mktemp)"
	run_long "packs update" exec_in_app deno run --allow-env --allow-read \
		--allow-write --allow-net --allow-run=unzip \
		"${APP_ROOT_IN_CONTAINER}/scripts/packs_update.ts" "$@" \
		>"${_pu_out}" || _pu_st=$?
	PACKS_UPDATE_OUT="$(cat "${_pu_out}")"
	rm -f "${_pu_out}"
	printf '%s\n' "${PACKS_UPDATE_OUT}" | grep -v '^LIMEDOC_' || true
	return "${_pu_st}"
}

app_running() {
	${COMPOSE_CMD} ps --quiet "${APP_SERVICE}" 2>/dev/null | grep -q .
}

app_has_packs_update() {
	exec_in_app test -f "${APP_ROOT_IN_CONTAINER}/scripts/packs_update.ts" \
		2>/dev/null
}

# After run_packs_update: in a prod deploy dir, move pack sidecars to the
# updated plugin versions and restart the app when templates changed (its
# production template cache only clears on restart). Plugins reload in the
# running app by themselves. <no_restart: 1 = only print what to run>
pack_update_followups() {
	_sids="$(printf '%s\n' "${PACKS_UPDATE_OUT:-}" | sed -n 's/^LIMEDOC_SIDECAR_UP=//p' | xargs)"
	if [ "${RUNTIME_CONTEXT:-}" != "prod" ] || [ "$1" = "1" ]; then
		if [ -n "${_sids}" ]; then
			info "updated sidecar packs: run ldcmd sidecar up ${_sids}"
		fi
		app_restart_followup "${PACKS_UPDATE_OUT:-}" 1
		return 0
	fi
	if [ -n "${_sids}" ] && [ "${PACK_FOLLOWUP_SIDECARS:-1}" = "1" ]; then
		info "moving sidecars to the updated versions: ${_sids}"
		# Subshell: a die inside sidecar up must not skip the restart below.
		# shellcheck disable=SC2086
		(cmd_sidecar_up ${_sids}) ||
			info "sidecar up failed — retry: ldcmd sidecar up ${_sids}"
	fi
	app_restart_followup "${PACKS_UPDATE_OUT:-}" 0
}

# app_restart_followup <packs:update|install output> <no_restart: 0|1>
# Restarts the app (prod deploy dir) for each LIMEDOC_APP_RESTART=<reason>:
# `plugins` — an in-process plugin changed; production keeps the build it
# imported first (or its failed import) until restart; `templates` — the
# production template cache clears only on restart. Without a marker it
# asks the running app (/api/health restartRequired): a re-run that installs
# nothing must still heal an app that kept a failed or old pack build.
# Elsewhere, or with no_restart=1, it only says what to run.
app_restart_followup() {
	_reasons="$(printf '%s\n' "$1" | sed -n 's/^LIMEDOC_APP_RESTART=//p' | sort -u | xargs)"
	if [ -z "${_reasons}" ] && app_restart_required; then
		_reasons=plugins
	fi
	[ -n "${_reasons}" ] || return 0
	_what="$(printf '%s' "${_reasons}" | sed 's/ / and /g')"
	if [ "${RUNTIME_CONTEXT:-}" != "prod" ] || [ "$2" = "1" ]; then
		info "updated ${_what}: restart the app (ldcmd down && ldcmd up)"
		return 0
	fi
	info "restarting the app so the updated ${_what} load"
	if ${COMPOSE_CMD} restart "${APP_SERVICE}"; then
		wait_app_healthy || info "the app is not healthy after the restart — check: ldcmd logs"
	else
		info "app restart failed — run: ldcmd up"
	fi
}

# app_restart_required — the running app reports packs that only load after
# a restart (/api/health "restartRequired": true, Limedoc 0.73.1+).
app_restart_required() {
	_rr_port="$(grep -E '^APP_HOST_PORT=' .env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true)"
	curl -sf --connect-timeout 3 --max-time 5 \
		"http://127.0.0.1:${_rr_port:-8000}/api/health" 2>/dev/null |
		grep -q '"restartRequired": *true'
}

# ── operator bootstrap (production, no app clone) ─────────────────────────────

DEFAULT_LIMEDOC_IMAGE="${DEFAULT_LIMEDOC_IMAGE:-git.belowtoxic.cloud/limedoc/limedoc:latest}"
DEFAULT_DEPLOY_BUNDLE_OWNER="limedoc"
DEFAULT_DEPLOY_BUNDLE_PACKAGE="limedoc"
DEFAULT_DEPLOY_BUNDLE_ARTIFACT="limedoc-deploy"
DEFAULT_DEPLOY_DIR_NAME="limedoc"

# ── release signatures ───────────────────────────────────────────────────────

# Ed25519 keys that sign Limedoc releases (OpenBao Transit, see the app's
# docs/security/RELEASE_SIGNATURES.md), as space-separated
# "keyId:base64(raw public key)". limedoc-deploy-* keys sign deploy bundles,
# limedoc-ldcmd-* keys sign ldcmd itself. Pinned here so a compromised or
# intercepted package registry cannot vouch for its own bundle.
# LDCMD_RELEASE_KEYS replaces the list (tests, rotation).
# Releases without a signature are refused unless LDCMD_REQUIRE_SIGNATURE=0.
LDCMD_REQUIRE_SIGNATURE_DEFAULT=1
LDCMD_RELEASE_KEYS_PINNED="limedoc-deploy-2026:yzUvCKMPadMH+1cZaQp9Fut4ld+/2CAYsBlenAIgfkI= limedoc-ldcmd-2026:4qDZN2kyvg16dhsjf0DwwvYcipa0Xut1iEAupCU4mxM="

# sha256_file <file> → lowercase hex on stdout; non-zero without a hash tool.
sha256_file() {
	if command -v sha256sum >/dev/null 2>&1; then
		sha256sum "$1" | awk '{print $1}'
	elif command -v shasum >/dev/null 2>&1; then
		shasum -a 256 "$1" | awk '{print $1}'
	elif command -v openssl >/dev/null 2>&1; then
		openssl dgst -sha256 -r "$1" | awk '{print $1}'
	else
		return 1
	fi
}

# verify_sha256_file <file> <sha256 file> — fails closed (no tool = die).
verify_sha256_file() {
	_vs_expected="$(awk '{print $1}' "$2" | head -1 | tr 'A-F' 'a-f')"
	case "${_vs_expected}" in
		*[!a-f0-9]*|"") die "malformed checksum file $(basename "$2")" ;;
	esac
	[ "${#_vs_expected}" -eq 64 ] || die "malformed checksum file $(basename "$2")"
	_vs_actual="$(sha256_file "$1")" ||
		die "need sha256sum, shasum or openssl to verify $(basename "$1")"
	[ "${_vs_actual}" = "${_vs_expected}" ] ||
		die "sha256 mismatch for $(basename "$1") (got ${_vs_actual}, expected ${_vs_expected})"
}

# json_str_field <file> <key> — first "key": "value" string (flat JSON).
json_str_field() {
	tr -d '\r\n' < "$1" |
		sed -n "s/.*\"$2\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" |
		head -1
}

# release_statement <artifact> <channel> <version> <sha256> — the signed
# message: compact JSON with sorted keys (what `jq -cnS` prints in CI).
release_statement() {
	printf '{"artifact":"%s","channel":"%s","sha256":"%s","statement":"limedoc.release.v1","version":"%s"}' \
		"$1" "$2" "$4" "$3"
}

# verify_release_signature <file> <sig.json> <artifact> <channel> [version]
# sig.json carries an Ed25519 signature (base64) over release_statement for
# <file>'s sha256, made with a pinned key for <artifact> (limedoc-deploy or
# ldcmd). <channel> is release or edge, so an edge build cannot pass as a
# release. Without [version] (the latest / edge aliases) the signed version
# is taken from sig.json and reported. Dies unless it verifies.
verify_release_signature() {
	_vr_file="$1"
	_vr_sigf="$2"
	_vr_art="$3"
	_vr_ch="$4"
	_vr_want="${5:-}"
	_vr_name="$(basename "${_vr_file}")"
	case "${_vr_art}" in
		limedoc-deploy|ldcmd) ;;
		*) die "unknown release artifact '${_vr_art}'" ;;
	esac
	case "${_vr_ch}" in
		release|edge) ;;
		*) die "unknown release channel '${_vr_ch}'" ;;
	esac
	command -v openssl >/dev/null 2>&1 ||
		die "openssl (3.x, Ed25519) required to verify the signature of ${_vr_name}"
	_vr_hash="$(sha256_file "${_vr_file}")" ||
		die "need sha256sum, shasum or openssl to hash ${_vr_name}"
	_vr_sha="$(json_str_field "${_vr_sigf}" sha256 | tr 'A-F' 'a-f')"
	_vr_sig="$(json_str_field "${_vr_sigf}" signature)"
	_vr_kid="$(json_str_field "${_vr_sigf}" keyId)"
	_vr_ver="$(json_str_field "${_vr_sigf}" version)"
	[ "${_vr_sha}" = "${_vr_hash}" ] ||
		die "signature for ${_vr_name} covers ${_vr_sha:-nothing}, file hashes to ${_vr_hash}"
	case "${_vr_sig}" in
		""|*[!A-Za-z0-9+/=]*) die "malformed signature in $(basename "${_vr_sigf}")" ;;
	esac
	case "${_vr_kid}" in
		""|*[!A-Za-z0-9._-]*) die "malformed keyId in $(basename "${_vr_sigf}")" ;;
	esac
	case "${_vr_ver}" in
		""|*[!A-Za-z0-9.+-]*) die "malformed version in $(basename "${_vr_sigf}")" ;;
	esac
	if [ -n "${_vr_want}" ] && [ "${_vr_ver}" != "${_vr_want}" ]; then
		die "${_vr_name} is signed as version ${_vr_ver}, expected ${_vr_want}"
	fi
	# A key only vouches for its own artifact.
	case "${_vr_art}:${_vr_kid}" in
		limedoc-deploy:limedoc-deploy-*|ldcmd:limedoc-ldcmd-*) ;;
		*) die "${_vr_name} is signed by key '${_vr_kid}', which does not sign ${_vr_art}" ;;
	esac
	_vr_pub=""
	for _vr_entry in ${LDCMD_RELEASE_KEYS:-${LDCMD_RELEASE_KEYS_PINNED}}; do
		if [ "${_vr_entry%%:*}" = "${_vr_kid}" ]; then
			_vr_pub="${_vr_entry#*:}"
		fi
	done
	[ -n "${_vr_pub}" ] ||
		die "${_vr_name} is signed by untrusted key '${_vr_kid}'"
	_vr_tmp="$(mktemp -d)"
	release_statement "${_vr_art}" "${_vr_ch}" "${_vr_ver}" "${_vr_hash}" \
		> "${_vr_tmp}/msg"
	printf '%s' "${_vr_sig}" | openssl base64 -d -A > "${_vr_tmp}/sig" 2>/dev/null
	# SubjectPublicKeyInfo DER for a raw Ed25519 key: fixed 12-byte prefix.
	{
		printf '\060\052\060\005\006\003\053\145\160\003\041\000'
		printf '%s' "${_vr_pub}" | openssl base64 -d -A 2>/dev/null
	} > "${_vr_tmp}/pub.der"
	if [ "$(wc -c < "${_vr_tmp}/pub.der" | tr -d ' ')" != "44" ] ||
		! openssl pkeyutl -verify -pubin -inkey "${_vr_tmp}/pub.der" \
			-keyform DER -rawin -in "${_vr_tmp}/msg" \
			-sigfile "${_vr_tmp}/sig" >/dev/null 2>&1; then
		rm -rf "${_vr_tmp}"
		die "release signature for ${_vr_name} does not verify (key ${_vr_kid}, ${_vr_ch} ${_vr_ver})"
	fi
	rm -rf "${_vr_tmp}"
	VERIFIED_RELEASE_VERSION="${_vr_ver}"
	info "release signature OK (${_vr_name}: ${_vr_art} ${_vr_ch} ${_vr_ver}, key ${_vr_kid})"
}

# fetch_optional <url> <out> → 0 fetched, 2 not published (404), 1 error.
fetch_optional() {
	_fo_code="$(ld_curl "${LDCMD_META_MAX_BYTES}" -sSL -o "$2" -w '%{http_code}' "$1" 2>/dev/null)" ||
		_fo_code="000"
	case "${_fo_code}" in
		200) return 0 ;;
		404) rm -f "$2"; return 2 ;;
		*) rm -f "$2"; return 1 ;;
	esac
}

# fetch_deploy_bundle <base url> <zip name> <version|latest|edge>
# Downloads the deploy bundle, checks its .sha256 (fail closed) and its
# release signature (fail closed). An unpublished signature is refused unless
# LDCMD_REQUIRE_SIGNATURE=0 (bundles from before releases were signed).
fetch_deploy_bundle() {
	_fb_base="$1"
	_fb_zip="$2"
	case "$3" in
		edge) _fb_ch=edge; _fb_ver="" ;;
		latest) _fb_ch=release; _fb_ver="" ;;
		*) _fb_ch=release; _fb_ver="$3" ;;
	esac
	_fb_sha="${_fb_zip}.sha256"
	_fb_sig="${_fb_zip}.sig.json"
	info "fetching deploy bundle ${_fb_base}/${_fb_zip}"
	ld_download "${LDCMD_BUNDLE_MAX_BYTES}" "${_fb_base}/${_fb_zip}" "${_fb_zip}" ||
		die "failed to download deploy bundle (set LIMEDOC_VERSION)"
	ld_download "${LDCMD_META_MAX_BYTES}" "${_fb_base}/${_fb_sha}" "${_fb_sha}" ||
		die "failed to download ${_fb_sha}"
	verify_sha256_file "${_fb_zip}" "${_fb_sha}"
	_fb_rc=0
	fetch_optional "${_fb_base}/${_fb_sig}" "${_fb_sig}" || _fb_rc=$?
	case "${_fb_rc}" in
		0)
			verify_release_signature "${_fb_zip}" "${_fb_sig}" limedoc-deploy \
				"${_fb_ch}" "${_fb_ver}"
			;;
		2)
			if [ "${LDCMD_REQUIRE_SIGNATURE:-${LDCMD_REQUIRE_SIGNATURE_DEFAULT}}" != "0" ]; then
				die "no release signature published for ${_fb_zip} (set LDCMD_REQUIRE_SIGNATURE=0 only for a bundle from before releases were signed)"
			fi
			info "WARNING: no release signature published for ${_fb_zip}; integrity is checked against the same-origin .sha256 only"
			;;
		*) die "failed to download ${_fb_sig}" ;;
	esac
	rm -f "${_fb_sha}" "${_fb_sig}"
}

# Single path segment: [A-Za-z0-9][A-Za-z0-9._-]*
validate_deploy_leaf() {
	_leaf="$1"
	case "${_leaf}" in
		''|'.'|'..') die "invalid deploy directory name: '${_leaf}'" ;;
		*/*) die "deploy directory must be a single name (no /): '${_leaf}'" ;;
	esac
	case "${_leaf}" in
		*[!A-Za-z0-9._-]*) die "deploy directory name has invalid characters: '${_leaf}'" ;;
	esac
	case "${_leaf}" in
		[A-Za-z0-9]*) ;;
		*) die "deploy directory name must start with alphanumeric: '${_leaf}'" ;;
	esac
}

# Directories that are never a deploy dir themselves (a sub-directory may be).
refuse_system_deploy_dir() {
	case "$1" in
		/|/etc|/usr|/bin|/sbin|/lib|/lib64|/boot|/dev|/proc|/sys|/run|/root|/tmp|/var|/home|/opt|/srv|/mnt|/media)
			die "refusing to install into system directory: $1"
			;;
	esac
	if [ -n "${HOME:-}" ] && [ "$1" = "${HOME%/}" ]; then
		die "refusing to install into the home directory itself: $1 (use a sub-directory)"
	fi
}

# A directory holding the deploy bundle: its compose file runs LIMEDOC_IMAGE.
# (is_limedoc_instance also wants the .env the wizard writes.)
is_limedoc_deploy_tree() {
	[ -f "$1/docker-compose.yml" ] && [ ! -L "$1/docker-compose.yml" ] &&
		grep -q 'LIMEDOC_IMAGE' "$1/docker-compose.yml" 2>/dev/null
}

# Bootstrap unpacks the bundle into the deploy dir and, run as root, hands
# the whole directory to the container user: only an empty directory or an
# existing deploy dir is taken ($2 = 1: --force).
check_bootstrap_target_dir() {
	[ -e "$1" ] || return 0
	[ -d "$1" ] || die "deploy path exists and is not a directory: $1"
	[ -L "$1" ] && die "deploy path is a symbolic link: $1 (name the directory itself)"
	[ -z "$(ls -A "$1" 2>/dev/null)" ] && return 0
	is_limedoc_deploy_tree "$1" && return 0
	if [ "$2" = "1" ]; then
		info "WARNING: --force: ${1} is not empty and is not a Limedoc deploy dir; bundle files are written into it and, as root, everything in it is handed to UID 10001"
		return 0
	fi
	die "$1 is not empty and is not a Limedoc deploy dir (no deploy bundle docker-compose.yml). Bootstrap writes the bundle there and, run as root, hands the whole directory to the container user. Pick an empty or new directory, or pass --force"
}

# Absolute path: safe basename, no .., not a system root, parent writable.
validate_absolute_deploy_dir() {
	_abs="$1"
	case "${_abs}" in
		*..*) die "deploy path must not contain ..: '${_abs}'" ;;
	esac
	_norm="${_abs%/}"
	[ -z "${_norm}" ] && _norm="/"
	refuse_system_deploy_dir "${_norm}"
	validate_deploy_leaf "$(basename "${_norm}")"
	_parent="$(dirname "${_norm}")"
	[ -d "${_parent}" ] || die "parent directory does not exist: ${_parent}"
	[ -w "${_parent}" ] || die "parent directory not writable: ${_parent}"
	if [ -e "${_norm}" ] && [ ! -d "${_norm}" ]; then
		die "deploy path exists and is not a directory: ${_norm}"
	fi
}

# Sets DEPLOY_DIR. Interactive prompt for leaf name under cwd when unset.
resolve_bootstrap_deploy_dir() {
	_cwd="$(pwd)"
	if [ -n "${LIMEDOC_DEPLOY_DIR}" ]; then
		_raw="${LIMEDOC_DEPLOY_DIR}"
	elif is_tty; then
		prompt_val _raw "Deploy directory name" "${DEFAULT_DEPLOY_DIR_NAME}"
	else
		_raw="${DEFAULT_DEPLOY_DIR_NAME}"
	fi
	case "${_raw}" in
		/*)
			validate_absolute_deploy_dir "${_raw}"
			DEPLOY_DIR="${_raw%/}"
			[ -z "${DEPLOY_DIR}" ] && DEPLOY_DIR="/"
			;;
		*)
			validate_deploy_leaf "${_raw}"
			DEPLOY_DIR="${_cwd%/}/${_raw}"
			refuse_system_deploy_dir "${DEPLOY_DIR}"
			;;
	esac
	require_plain_path "deploy dir" "${DEPLOY_DIR}"
}

# ── prod deploy + pack-owned sidecars ─────────────────────────────────────────

is_pack_dev_cwd() {
	[ -f "compose.dev.yml" ] || [ -f "limedoc.project.json" ]
}

is_prod_deploy_layout() {
	_dir="${1:-.}"
	[ -f "${_dir}/docker-compose.yml" ] && [ -f "${_dir}/.env" ] &&
		[ ! -f "${_dir}/compose.dev.yml" ]
}

# ── instances (several deploy dirs per host) ─────────────────────────────────
#
# An instance is a prod deploy dir; its id is the dir name (= compose project
# name). ldcmd finds them in its registry (written by bootstrap / use), in the
# compose labels of Docker containers (running or stopped) and under
# LDCMD_INSTANCE_SEARCH. `ldcmd use <id>` selects the one operator commands
# work on; `ldcmd -i <id> <command>` or LIMEDOC_DEPLOY_DIR override it once.

LDCMD_STATE_DIR="${LDCMD_STATE_DIR:-${XDG_STATE_HOME:-${HOME:-/root}/.local/state}/ldcmd}"
LDCMD_INSTANCE_SEARCH="${LDCMD_INSTANCE_SEARCH:-/opt /srv ${HOME:-/root}}"

# Canonical absolute path of an existing directory (empty if missing).
canon_dir() {
	(cd "$1" 2>/dev/null && pwd -P) || true
}

# A prod deploy dir whose compose file runs the Limedoc app image.
is_limedoc_instance() {
	is_prod_deploy_layout "$1" &&
		grep -q 'LIMEDOC_IMAGE' "$1/docker-compose.yml" 2>/dev/null
}

instance_id() {
	basename "$1"
}

register_instance() {
	_ri_dir="$(canon_dir "$1")"
	[ -n "${_ri_dir}" ] || return 0
	mkdir -p "${LDCMD_STATE_DIR}" 2>/dev/null || return 0
	_ri_reg="${LDCMD_STATE_DIR}/instances"
	if ! grep -qxF "${_ri_dir}" "${_ri_reg}" 2>/dev/null; then
		printf '%s\n' "${_ri_dir}" >> "${_ri_reg}" 2>/dev/null || true
	fi
}

# The `ldcmd use` selection (canonical dir), or empty.
selected_instance_dir() {
	[ -f "${LDCMD_STATE_DIR}/current" ] || return 0
	head -1 "${LDCMD_STATE_DIR}/current" | tr -d '\r'
}

# Every Limedoc instance on this host, one canonical dir per line, sorted.
discover_instances() {
	{
		[ -f "${LDCMD_STATE_DIR}/instances" ] &&
			cat "${LDCMD_STATE_DIR}/instances"
		selected_instance_dir
		if command -v docker >/dev/null 2>&1; then
			docker ps -a --filter label=com.docker.compose.service=app \
				--format '{{.Label "com.docker.compose.project.working_dir"}}' \
				2>/dev/null || true
		fi
		for _di_root in ${LDCMD_INSTANCE_SEARCH}; do
			for _di_d in "${_di_root}"/*/; do
				[ -d "${_di_d}" ] && printf '%s\n' "${_di_d%/}"
			done
		done
		is_prod_deploy_layout "$(pwd)" && pwd
	} 2>/dev/null | while IFS= read -r _di_d; do
		[ -n "${_di_d}" ] || continue
		_di_c="$(canon_dir "${_di_d}")"
		[ -n "${_di_c}" ] && is_limedoc_instance "${_di_c}" &&
			printf '%s\n' "${_di_c}"
	done | sort -u
}

# Resolve an instance id (dir name) or path to its canonical dir; dies when
# unknown or ambiguous.
resolve_instance_ref() {
	_ir_ref="$1"
	case "${_ir_ref}" in
		/*|./*|../*|.)
			_ir_dir="$(canon_dir "${_ir_ref}")"
			[ -n "${_ir_dir}" ] && is_limedoc_instance "${_ir_dir}" ||
				die "${_ir_ref} is not a Limedoc instance (need docker-compose.yml + .env of a deploy bundle)"
			printf '%s\n' "${_ir_dir}"
			return 0
			;;
	esac
	_ir_hits="$(discover_instances | while IFS= read -r _ir_d; do
		if [ "$(instance_id "${_ir_d}")" = "${_ir_ref}" ]; then
			printf '%s\n' "${_ir_d}"
		fi
	done)"
	_ir_n="$(printf '%s' "${_ir_hits}" | grep -c . || true)"
	case "${_ir_n}" in
		0) die "no instance '${_ir_ref}' on this host (ldcmd list shows them; a path works too: ldcmd use /abs/dir)" ;;
		1) printf '%s\n' "${_ir_hits}" ;;
		*)
			info "instance id '${_ir_ref}' is ambiguous:"
			printf '%s\n' "${_ir_hits}" | sed 's/^/ldcmd:   /' >&2
			die "pass the path instead: ldcmd use /abs/dir"
			;;
	esac
}

# Core container state of an instance: running | stopped | partial (n/m) | no containers
instance_state() {
	_is_all="$(docker ps -a --filter "label=com.docker.compose.project=$(instance_id "$1")" \
		--filter "label=com.docker.compose.project.working_dir=$1" \
		--format '{{.State}}' 2>/dev/null || true)"
	_is_total="$(printf '%s' "${_is_all}" | grep -c . || true)"
	_is_run="$(printf '%s' "${_is_all}" | grep -c '^running$' || true)"
	if [ "${_is_total}" -eq 0 ]; then
		echo "no containers"
	elif [ "${_is_run}" -eq "${_is_total}" ]; then
		echo "running"
	elif [ "${_is_run}" -eq 0 ]; then
		echo "stopped"
	else
		echo "partial (${_is_run}/${_is_total})"
	fi
}

cmd_list() {
	[ $# -eq 0 ] || die "list: takes no arguments"
	_li_sel="$(selected_instance_dir)"
	_li_all="$(discover_instances)"
	if [ -z "${_li_all}" ]; then
		info "no Limedoc instance found (looked in ${LDCMD_STATE_DIR}/instances, Docker, ${LDCMD_INSTANCE_SEARCH})"
		info "set one up: ldcmd bootstrap — or register a deploy dir: ldcmd use /abs/dir"
		return 0
	fi
	printf '  %-20s %-16s %-48s %s\n' ID STATE IMAGE DIR
	printf '%s\n' "${_li_all}" | while IFS= read -r _li_d; do
		_li_mark=' '
		[ "${_li_d}" = "${_li_sel}" ] && _li_mark='*'
		_li_img="$(grep -E '^LIMEDOC_IMAGE=' "${_li_d}/.env" 2>/dev/null |
			head -1 | cut -d= -f2- | tr -d "\r\"'")"
		printf '%s %-20s %-16s %-48s %s\n' "${_li_mark}" \
			"$(instance_id "${_li_d}")" "$(instance_state "${_li_d}")" \
			"${_li_img:-${DEFAULT_LIMEDOC_IMAGE} (default)}" "${_li_d}"
	done
	if [ -n "${_li_sel}" ] && ! printf '%s\n' "${_li_all}" | grep -qxF "${_li_sel}"; then
		info "the selected instance ${_li_sel} no longer exists (ldcmd use <id> to pick another)"
	elif [ -z "${_li_sel}" ]; then
		info "no instance selected; pick one: ldcmd use <id>"
	fi
}

cmd_use() {
	case "${1:-}" in
		"")
			_us_sel="$(selected_instance_dir)"
			if [ -z "${_us_sel}" ]; then
				info "no instance selected (ldcmd list; ldcmd use <id>)"
			else
				echo "$(instance_id "${_us_sel}") ${_us_sel}"
			fi
			;;
		--clear|none)
			rm -f "${LDCMD_STATE_DIR}/current"
			info "instance selection cleared"
			;;
		-*) die "use: unknown option '$1' (use <id|path> | use --clear)" ;;
		*)
			[ $# -eq 1 ] || die "use: takes one instance id or path"
			_us_dir="$(resolve_instance_ref "$1")"
			mkdir -p "${LDCMD_STATE_DIR}" ||
				die "cannot create ${LDCMD_STATE_DIR}"
			printf '%s\n' "${_us_dir}" > "${LDCMD_STATE_DIR}/current"
			register_instance "${_us_dir}"
			info "now using instance $(instance_id "${_us_dir}") (${_us_dir}, $(instance_state "${_us_dir}"))"
			;;
	esac
}

# Operator commands work on a prod instance unless the cwd is a pack-dev
# checkout and no instance was named explicitly.
prod_context() {
	[ -n "${LIMEDOC_DEPLOY_DIR}" ] || ! is_pack_dev_cwd
}

# Pick DEPLOY_DIR: LIMEDOC_DEPLOY_DIR / -i, else the `use` selection, else the
# cwd, else the only instance on the host. Says which one and why.
select_prod_instance() {
	_sp_cwd="$(pwd)"
	if [ -n "${LIMEDOC_DEPLOY_DIR}" ]; then
		DEPLOY_DIR="${LIMEDOC_DEPLOY_DIR%/}"
		_sp_why="${LDCMD_INSTANCE_SOURCE:-LIMEDOC_DEPLOY_DIR}"
	elif _sp_sel="$(selected_instance_dir)" && [ -n "${_sp_sel}" ]; then
		is_prod_deploy_layout "${_sp_sel}" ||
			die "the selected instance ${_sp_sel} is gone (no docker-compose.yml + .env); pick another: ldcmd list, ldcmd use <id>"
		DEPLOY_DIR="${_sp_sel}"
		_sp_why="selected with ldcmd use"
		if is_prod_deploy_layout "${_sp_cwd}" &&
			[ "$(canon_dir "${_sp_cwd}")" != "${_sp_sel}" ]; then
			info "note: the current directory is instance $(instance_id "${_sp_cwd}"), but the selected instance is used (switch: ldcmd use $(instance_id "${_sp_cwd}"))"
		fi
	elif is_prod_deploy_layout "${_sp_cwd}"; then
		DEPLOY_DIR="${_sp_cwd}"
		_sp_why="current directory"
	else
		_sp_all="$(discover_instances)"
		_sp_n="$(printf '%s' "${_sp_all}" | grep -c . || true)"
		case "${_sp_n}" in
			0) die "no Limedoc instance found on this host. Set one up: ldcmd bootstrap — or point at one: ldcmd use /abs/dir" ;;
			1)
				DEPLOY_DIR="${_sp_all}"
				_sp_why="the only instance on this host"
				;;
			*)
				info "${_sp_n} instances on this host:"
				printf '%s\n' "${_sp_all}" | while IFS= read -r _sp_d; do
					info "  $(instance_id "${_sp_d}")  ${_sp_d}"
				done
				die "pick one: ldcmd use <id> (or once: ldcmd -i <id> <command>)"
				;;
		esac
	fi
	require_plain_path "deploy dir" "${DEPLOY_DIR}"
	export LIMEDOC_DEPLOY_DIR="${DEPLOY_DIR}"
	export LDCMD_INSTANCE_SOURCE="${_sp_why}"
	if [ -z "${LDCMD_INSTANCE_ANNOUNCED:-}" ]; then
		info "instance $(instance_id "${DEPLOY_DIR}") (${DEPLOY_DIR}; ${_sp_why})"
		export LDCMD_INSTANCE_ANNOUNCED=1
	fi
}

# Resolve DEPLOY_DIR for operator commands (see select_prod_instance).
resolve_prod_deploy_dir() {
	select_prod_instance
	cd "${DEPLOY_DIR}" || die "cannot cd ${DEPLOY_DIR}"
	# Match app env_file / configure resolveDeployEnvPath (do not clobber an
	# explicit LIMEDOC_ENV_FILE; else read pointer from deploy .env).
	if [ -z "${LIMEDOC_ENV_FILE:-}" ] && [ -f "${DEPLOY_DIR}/.env" ]; then
		LIMEDOC_ENV_FILE="$(grep -E '^LIMEDOC_ENV_FILE=' "${DEPLOY_DIR}/.env" 2>/dev/null |
			head -1 | cut -d= -f2- | tr -d '\r' | tr -d '"' | tr -d "'")"
	fi
	export LIMEDOC_ENV_FILE="${LIMEDOC_ENV_FILE:-.env}"
	require_plain_path "LIMEDOC_ENV_FILE" "${LIMEDOC_ENV_FILE}"
	[ -z "${LIMEDOC_PLUGINS_DIR:-}" ] ||
		require_plain_path "LIMEDOC_PLUGINS_DIR" "${LIMEDOC_PLUGINS_DIR}"
}

# Absolute path for docker compose --env-file (same rules as resolveDeployEnvPath).
deploy_env_file() {
	_ptr="${LIMEDOC_ENV_FILE:-.env}"
	case "${_ptr}" in
		/*) printf '%s\n' "${_ptr}" ;;
		*) printf '%s\n' "${DEPLOY_DIR}/${_ptr}" ;;
	esac
}

# Compose project name = deploy directory basename (multi-instance on one host).
prod_compose_project_name() {
	basename "${DEPLOY_DIR}"
}

sidecar_compose_project_name() {
	printf '%s-sidecar-%s\n' "$(prod_compose_project_name)" "$1"
}

prod_docker_network_name() {
	printf '%s_internal\n' "$(prod_compose_project_name)"
}

# Seed DOCKER_NETWORK_NAME when missing/empty; never overwrite a set value.
seed_docker_network_name() {
	_envf="$(deploy_env_file)"
	[ -f "${_envf}" ] || return 0
	_cur="$(grep -E '^DOCKER_NETWORK_NAME=' "${_envf}" 2>/dev/null | head -1 |
		cut -d= -f2- | tr -d '\r' | tr -d '"' | tr -d "'" || true)"
	[ -n "${_cur}" ] && return 0
	_net="$(prod_docker_network_name)"
	printf '\nDOCKER_NETWORK_NAME=%s\n' "${_net}" >> "${_envf}"
	info "seeded DOCKER_NETWORK_NAME=${_net} in ${_envf}"
}

# Core compose overlay from `ldcmd sidecar isolate` (see cmd_sidecar_isolate).
ISOLATION_OVERLAY_FILE="docker-compose.isolation.yml"
# Compose's conventional override name; ldcmd names its files explicitly, so
# Compose would not pick it up by itself.
OPERATOR_OVERLAY_FILE="docker-compose.override.yml"

prod_core_compose_args() {
	_envf="$(deploy_env_file)"
	seed_docker_network_name
	_proj="$(prod_compose_project_name)"
	# --project-directory so relative LIMEDOC_DATA_MOUNT / VECTORSEARCH_CACHE_MOUNT
	# resolve against the deploy dir (not the compose file path).
	# --project-name = deploy leaf (not hardcoded compose `name:`).
	COMPOSE_ARGS="--project-directory ${DEPLOY_DIR} --project-name ${_proj} -f ${DEPLOY_DIR}/docker-compose.yml --env-file ${_envf}"
	[ -f "${DEPLOY_DIR}/docker-compose.registry.yml" ] &&
		COMPOSE_ARGS="--project-directory ${DEPLOY_DIR} --project-name ${_proj} -f ${DEPLOY_DIR}/docker-compose.yml -f ${DEPLOY_DIR}/docker-compose.registry.yml --env-file ${_envf}"
	if [ -f "${DEPLOY_DIR}/docker-compose.wizard.publish.yml" ]; then
		_mode="$(grep -E '^DEPLOY_NETWORK_MODE=' "${_envf}" 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true)"
		[ "${_mode}" = "external" ] &&
			COMPOSE_ARGS="${COMPOSE_ARGS} -f ${DEPLOY_DIR}/docker-compose.wizard.publish.yml"
	fi
	# Written by `ldcmd sidecar isolate web-render` (redis + app on the
	# worker's own network).
	if [ -f "${DEPLOY_DIR}/${ISOLATION_OVERLAY_FILE}" ]; then
		COMPOSE_ARGS="${COMPOSE_ARGS} -f ${DEPLOY_DIR}/${ISOLATION_OVERLAY_FILE}"
	fi
	# The operator's own overlay (resource limits, extra mounts), last so it
	# wins. Never written or replaced by ldcmd.
	if [ -f "${DEPLOY_DIR}/${OPERATOR_OVERLAY_FILE}" ]; then
		COMPOSE_ARGS="${COMPOSE_ARGS} -f ${DEPLOY_DIR}/${OPERATOR_OVERLAY_FILE}"
	fi
	PROFILE_ARGS="--profile redis --profile app"
}

prod_core_up() {
	resolve_prod_deploy_dir
	prod_core_compose_args
	[ ! -f "${DEPLOY_DIR}/${OPERATOR_OVERLAY_FILE}" ] ||
		info "applying your overlay ${OPERATOR_OVERLAY_FILE}"
	step "pulling core images (redis + app)"
	# shellcheck disable=SC2086
	run_long "image pull" docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} pull ||
		info "pull warnings — continuing with the images already on this host"
	step "starting core containers (redis + app)"
	# shellcheck disable=SC2086
	run_long "compose up" docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} up -d ||
		die "core compose up failed"
}

prod_core_down() {
	resolve_prod_deploy_dir
	prod_core_compose_args
	info "core compose down in ${DEPLOY_DIR}"
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} down "$@" || true
}

# Print packs:sidecars JSON from running app (stdout).
prod_packs_sidecars_json() {
	resolve_prod_deploy_dir
	prod_core_compose_args
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} exec -T app \
		deno task -q packs:sidecars
}

sidecar_active_path() {
	echo "${DEPLOY_DIR}/sidecars/active.json"
}

# Update sidecars/active.json: merge|replace (id version project …) or remove (id …).
sidecar_update_active() {
	_mode="$1"
	shift
	_path="$(sidecar_active_path)"
	mkdir -p "${DEPLOY_DIR}/sidecars"
	if ! command -v python3 >/dev/null 2>&1; then
		info "python3 missing — skip writing sidecars/active.json"
		return 0
	fi
	ACTIVE_PATH="${_path}" ACTIVE_MODE="${_mode}" python3 - "$@" <<'PY'
import json, os, sys

path = os.environ["ACTIVE_PATH"]
mode = os.environ.get("ACTIVE_MODE", "replace")
args = sys.argv[1:]

existing = {"v": 1, "projects": []}
if os.path.isfile(path):
    try:
        with open(path, encoding="utf-8") as f:
            existing = json.load(f)
    except (json.JSONDecodeError, OSError):
        pass

by_id = {p.get("id"): p for p in (existing.get("projects") or []) if p.get("id")}

if mode == "remove":
    for pid in args:
        by_id.pop(pid, None)
elif mode == "merge":
    i = 0
    while i + 2 < len(args):
        by_id[args[i]] = {
            "id": args[i],
            "version": args[i + 1],
            "project": args[i + 2],
        }
        i += 3
elif mode == "replace":
    by_id = {}
    i = 0
    while i + 2 < len(args):
        by_id[args[i]] = {
            "id": args[i],
            "version": args[i + 1],
            "project": args[i + 2],
        }
        i += 3
else:
    raise SystemExit(f"unknown active mode: {mode}")

projects = sorted(by_id.values(), key=lambda p: p.get("id") or "")
data = {"v": 1, "projects": projects}
with open(path, "w", encoding="utf-8") as f:
    json.dump(data, f, indent="\t")
    f.write("\n")
PY
}

# Marker written into a sidecar tree only after full verification succeeded.
SIDECAR_VERIFIED_MARKER=".ldcmd-verified"

# Image used to verify downloaded packs: LIMEDOC_IMAGE → deploy .env →
# DEFAULT_LIMEDOC_IMAGE (the app image carries the trust root + verifier).
sidecar_verify_image() {
	_svi="${LIMEDOC_IMAGE:-}"
	if [ -z "${_svi}" ] && [ -f "${DEPLOY_DIR}/.env" ]; then
		_svi="$(grep -E '^LIMEDOC_IMAGE=' "${DEPLOY_DIR}/.env" 2>/dev/null |
			head -1 | cut -d= -f2- | tr -d '\r' | tr -d '"' | tr -d "'")"
	fi
	[ -n "${_svi}" ] || _svi="${DEFAULT_LIMEDOC_IMAGE}"
	echo "${_svi}"
}

# sidecar_verify_tree <tree> <sha256 file> <sig file> <id> <version> [prune]
# Runs scripts/pack_verify_dir.ts in the Limedoc image: trust-root-signed
# registry, pack content hash, sig.json identity and Ed25519 signature.
# `prune` (ldcmd's own staging trees) first deletes everything outside the
# hashed set, so a zip's unsigned extras never reach compose.
# Prints the verified content hash; dies on any failure (fail closed).
sidecar_verify_tree() {
	_svt_tree="$1"
	_svt_sha="$2"
	_svt_sig="$3"
	_svt_id="$4"
	_svt_ver="$5"
	_svt_prune="${6:-}"
	command -v docker >/dev/null 2>&1 ||
		die "docker is required to verify sidecar pack ${_svt_id}@${_svt_ver}"
	_svt_img="$(sidecar_verify_image)"
	if ! docker image inspect "${_svt_img}" >/dev/null 2>&1; then
		info "pulling ${_svt_img} for pack signature verification"
		docker pull "${_svt_img}" >/dev/null 2>&1 ||
			die "cannot pull ${_svt_img} (needed to verify ${_svt_id}@${_svt_ver}); set LIMEDOC_IMAGE to a reachable Limedoc image"
	fi
	_svt_v1=""
	if [ -n "${TRUST_ACCEPT_V1_PACK_SIGNATURES:-}" ]; then
		_svt_v1="-e TRUST_ACCEPT_V1_PACK_SIGNATURES=${TRUST_ACCEPT_V1_PACK_SIGNATURES}"
	fi
	info "verifying pack signature for ${_svt_id}@${_svt_ver} via ${_svt_img}"
	_svt_err="$(mktemp)"
	_svt_mode=ro
	_svt_pargs=""
	if [ "${_svt_prune}" = "prune" ]; then
		_svt_mode=rw
		_svt_pargs="--prune"
	fi
	# shellcheck disable=SC2086
	_svt_out="$(docker run --rm \
		-v "${_svt_tree}:/pack:${_svt_mode}" \
		-v "${_svt_sha}:/verify/pack.sha256:ro" \
		-v "${_svt_sig}:/verify/pack.sig.json:ro" \
		${_svt_v1} \
		-w /app \
		"${_svt_img}" \
		deno run --allow-read --allow-write=/pack --allow-net --allow-env \
		/app/scripts/pack_verify_dir.ts ${_svt_pargs} \
		--kind plugin --id "${_svt_id}" --version "${_svt_ver}" \
		--sha256 /verify/pack.sha256 --sig /verify/pack.sig.json /pack \
		2>"${_svt_err}")" || _svt_out=""
	_svt_reason="$(grep -v '^pruned outside' "${_svt_err}" 2>/dev/null | head -5 | tr '\n' ' ')"
	_svt_pruned="$(sed -n 's/^pruned outside the hashed set: //p' "${_svt_err}" 2>/dev/null)"
	rm -f "${_svt_err}"
	[ -n "${_svt_pruned}" ] &&
		info "removed files outside the signed pack ${_svt_id}@${_svt_ver}: ${_svt_pruned}"
	case "${_svt_out}" in
		"OK "*) ;;
		*)
			case "${_svt_reason}" in
				*"unknown or incomplete option --prune"*)
					# App image before 0.4.5: verify without pruning.
					info "WARNING: ${_svt_img} cannot prune files outside the signed pack (upgrade LIMEDOC_IMAGE to 0.4.5+)"
					sidecar_verify_tree "${_svt_tree}" "${_svt_sha}" "${_svt_sig}" \
						"${_svt_id}" "${_svt_ver}"
					return $?
					;;
				*"Module not found"*|*pack_verify_dir.ts*)
					die "pack verification unavailable in ${_svt_img} (image too old; upgrade LIMEDOC_IMAGE to a release that ships scripts/pack_verify_dir.ts)"
					;;
			esac
			die "pack verification failed for ${_svt_id}@${_svt_ver}: ${_svt_reason:-no output from verifier}"
			;;
	esac
	_svt_hash="$(printf '%s\n' "${_svt_out}" | awk 'NR==1{print $2}')"
	case "${_svt_hash}" in
		*[!a-f0-9]*|'') die "pack verifier returned no content hash" ;;
	esac
	info "pack signature OK (${_svt_out})"
	echo "${_svt_hash}"
}

# Download pack zip + .sha256 + .sig.json into $DEPLOY_DIR/sidecars/<id>@<version>/,
# verify (hash + Ed25519 signature) in a staging dir, then move into place.
# Pack .sha256 is a bare hex content hash of the pack tree (hashPackDir), not a
# GNU sha256sum line over the zip bytes — same as Pack Store / fetchStoreSha256.
# Fails closed: nothing is returned unless verification succeeded.
sidecar_download_pack() {
	_id="$1"
	_ver="$2"
	case "${_id}" in
		''|*[!a-z0-9-]*) die "invalid sidecar pack id: '${_id}'" ;;
	esac
	case "${_ver}" in
		''|unknown|*[!0-9A-Za-z.+-]*) die "invalid sidecar pack version for ${_id}: '${_ver}'" ;;
	esac
	_dest="${DEPLOY_DIR}/sidecars/${_id}@${_ver}"
	if [ -f "${_dest}/${SIDECAR_VERIFIED_MARKER}" ] &&
		{ [ -f "${_dest}/deploy.json" ] || [ -f "${_dest}/worker/docker-compose.yml" ]; }; then
		echo "${_dest}"
		return 0
	fi
	_reg="${PACKAGE_REGISTRY_URL:-${DEFAULT_PACKAGE_REGISTRY_URL}}"
	_owner="${PACKAGE_OWNER_DEFAULT:-limedoc-plugins}"
	_base="${_reg}/api/packages/${_owner}/generic/${_id}/${_ver}"
	_zip="${_id}-${_ver}.zip"
	_sha="${_id}-${_ver}.sha256"
	_sigf="${_id}-${_ver}.sig.json"
	_stage="${_dest}.tmp"
	# An existing tree without the marker was never verified: drop it.
	rm -rf "${_dest}" "${_stage}"
	mkdir -p "${_stage}/tree"
	info "downloading sidecar pack ${_id}@${_ver}"
	ld_download "${LDCMD_PACK_MAX_BYTES}" "${_base}/${_zip}" "${_stage}/${_zip}" ||
		{ rm -rf "${_stage}"; die "failed to download ${_base}/${_zip}"; }
	ld_download "${LDCMD_META_MAX_BYTES}" "${_base}/${_sha}" "${_stage}/${_sha}" ||
		{ rm -rf "${_stage}"; die "failed to download ${_base}/${_sha}"; }
	ld_download "${LDCMD_META_MAX_BYTES}" "${_base}/${_sigf}" "${_stage}/${_sigf}" ||
		{ rm -rf "${_stage}"; die "failed to download ${_base}/${_sigf} (sidecar packs must be signed)"; }
	_expected="$(awk '{print $1; exit}' "${_stage}/${_sha}" | tr -d '\r' | tr 'A-F' 'a-f')"
	case "${_expected}" in
		*[!a-f0-9]* | '')
			rm -rf "${_stage}"
			die "invalid pack content hash in ${_sha} (expected 64 hex chars)"
			;;
	esac
	[ "${#_expected}" -eq 64 ] ||
		{ rm -rf "${_stage}"; die "invalid pack content hash in ${_sha} (got ${#_expected} chars, need 64)"; }
	grep -q '"signature"' "${_stage}/${_sigf}" 2>/dev/null ||
		{ rm -rf "${_stage}"; die "invalid ${_sigf} (no signature field)"; }
	safe_unzip "${_stage}/${_zip}" "${_stage}/tree" \
		"${LDCMD_PACK_MAX_EXTRACT_BYTES}" -o -q ||
		{ rm -rf "${_stage}"; die "extract failed for ${_id}@${_ver} (size limits: LDCMD_PACK_MAX_EXTRACT_BYTES, LDCMD_ZIP_MAX_ENTRIES)"; }
	_tree="${_stage}/tree"
	# Zip may nest as <id>.plugin/ — normalize to flat tree with deploy.json at root.
	if [ ! -f "${_tree}/deploy.json" ] && [ -f "${_tree}/${_id}.plugin/deploy.json" ]; then
		_nested="${_tree}/${_id}.plugin"
		for _f in "${_nested}"/* "${_nested}"/.[!.]*; do
			[ -e "${_f}" ] || continue
			mv "${_f}" "${_tree}/" 2>/dev/null || true
		done
		rmdir "${_nested}" 2>/dev/null || true
	fi
	[ -f "${_tree}/deploy.json" ] ||
		{ rm -rf "${_stage}"; die "no deploy.json in ${_id}@${_ver} after extract"; }
	# Verify in a subshell so a die there still lets us clean the staging dir.
	if ! _verified="$(sidecar_verify_tree "${_tree}" "${_stage}/${_sha}" \
		"${_stage}/${_sigf}" "${_id}" "${_ver}" prune)"; then
		rm -rf "${_stage}"
		die "refusing to use unverified sidecar pack ${_id}@${_ver}"
	fi
	[ "${_verified}" = "${_expected}" ] ||
		{ rm -rf "${_stage}"; die "verified hash ${_verified} does not match ${_sha} (${_expected})"; }
	printf '%s\n' "${_verified}" > "${_tree}/${SIDECAR_VERIFIED_MARKER}"
	rm -rf "${_dest}"
	mkdir -p "$(dirname "${_dest}")"
	mv "${_tree}" "${_dest}" ||
		{ rm -rf "${_stage}"; die "cannot move verified tree to ${_dest}"; }
	rm -rf "${_stage}"
	echo "${_dest}"
}

# sidecar_verify_plugins_dir_tree <tree> <id> <version> — a LIMEDOC_PLUGINS_DIR
# tree runs compose on this host, so it must match the signed release of its
# version (fetches only the .sha256 + .sig.json). LDCMD_TRUST_PLUGINS_DIR=1
# skips this for a checkout only you can write (pack development).
sidecar_verify_plugins_dir_tree() {
	_spd_tree="$1"
	_spd_id="$2"
	_spd_ver="$3"
	if [ "${LDCMD_TRUST_PLUGINS_DIR:-}" = "1" ]; then
		info "WARNING: using ${_spd_tree} unverified (LDCMD_TRUST_PLUGINS_DIR=1)"
		return 0
	fi
	case "${_spd_ver}" in
		''|unknown|*[!0-9A-Za-z.+-]*) die "invalid sidecar pack version for ${_spd_id}: '${_spd_ver}'" ;;
	esac
	_spd_base="${PACKAGE_REGISTRY_URL:-${DEFAULT_PACKAGE_REGISTRY_URL}}/api/packages/${PACKAGE_OWNER_DEFAULT:-limedoc-plugins}/generic/${_spd_id}/${_spd_ver}"
	_spd_tmp="$(mktemp -d)"
	if ! ld_download "${LDCMD_META_MAX_BYTES}" "${_spd_base}/${_spd_id}-${_spd_ver}.sha256" "${_spd_tmp}/pack.sha256" ||
		! ld_download "${LDCMD_META_MAX_BYTES}" "${_spd_base}/${_spd_id}-${_spd_ver}.sig.json" "${_spd_tmp}/pack.sig.json"; then
		rm -rf "${_spd_tmp}"
		die "cannot fetch the signature of ${_spd_id}@${_spd_ver} to verify ${_spd_tree} (LDCMD_TRUST_PLUGINS_DIR=1 for a pack checkout you control)"
	fi
	if ! (sidecar_verify_tree "${_spd_tree}" "${_spd_tmp}/pack.sha256" \
		"${_spd_tmp}/pack.sig.json" "${_spd_id}" "${_spd_ver}" >/dev/null); then
		rm -rf "${_spd_tmp}"
		die "${_spd_tree} does not match the signed ${_spd_id}@${_spd_ver} (LDCMD_TRUST_PLUGINS_DIR=1 for a pack checkout you control)"
	fi
	rm -rf "${_spd_tmp}"
}

# Resolve host pack tree: LIMEDOC_PLUGINS_DIR bind-mount (verified), else the
# downloaded, verified archive.
sidecar_resolve_tree() {
	_id="$1"
	_ver="$2"
	if [ -n "${LIMEDOC_PLUGINS_DIR}" ] && [ -d "${LIMEDOC_PLUGINS_DIR}/${_id}.plugin" ]; then
		sidecar_verify_plugins_dir_tree "${LIMEDOC_PLUGINS_DIR}/${_id}.plugin" \
			"${_id}" "${_ver}" >&2
		echo "${LIMEDOC_PLUGINS_DIR}/${_id}.plugin"
		return 0
	fi
	sidecar_download_pack "${_id}" "${_ver}"
}

# Map host pack tree to in-container path (/deploy/… or /plugins-host/…).
sidecar_tree_for_container() {
	_host="$1"
	_host="${_host%/}"
	_deploy="${DEPLOY_DIR%/}"
	case "${_host}" in
		"${_deploy}"/*)
			echo "/deploy/${_host#${_deploy}/}"
			return 0
			;;
		"${_deploy}")
			echo "/deploy"
			return 0
			;;
	esac
	if [ -n "${LIMEDOC_PLUGINS_DIR}" ]; then
		_plugins="${LIMEDOC_PLUGINS_DIR%/}"
		case "${_host}" in
			"${_plugins}"/*)
				echo "/plugins-host/${_host#${_plugins}/}"
				return 0
				;;
			"${_plugins}")
				echo "/plugins-host"
				return 0
				;;
		esac
	fi
	die "sidecar tree outside mounted paths: ${_host} (expected under ${DEPLOY_DIR} or LIMEDOC_PLUGINS_DIR)"
}

# Optional bind-mount when pack trees live under LIMEDOC_PLUGINS_DIR.
sidecar_configure_mount_args() {
	if [ -n "${LIMEDOC_PLUGINS_DIR}" ] && [ -d "${LIMEDOC_PLUGINS_DIR}" ]; then
		echo "-v ${LIMEDOC_PLUGINS_DIR}:/plugins-host:ro"
	fi
}

sidecar_compose_files_from_deploy() {
	_tree="$1"
	_deploy="${_tree}/deploy.json"
	[ -f "${_deploy}" ] || die "missing ${_deploy}"
	python3 - "${_deploy}" <<'PY'
import json, sys
m = json.load(open(sys.argv[1], encoding="utf-8"))
files = m.get("composeFiles") or []
if not isinstance(files, list) or not files:
    raise SystemExit("deploy.json has no composeFiles")
print("\n".join(f if isinstance(f, str) else "" for f in files))
PY
}

# A composeFiles entry is a relative path inside the pack tree: no option,
# no absolute path, no "..", nothing the shell would split or expand.
valid_compose_rel() {
	case "$1" in
		""|-*|/*|*..*|*[!A-Za-z0-9._/-]*) return 1 ;;
	esac
}

# Prints the validated composeFiles of a pack tree, one per line.
sidecar_compose_files_checked() {
	_cf_list="$(sidecar_compose_files_from_deploy "$1")" ||
		die "cannot read composeFiles from $1/deploy.json"
	[ -n "${_cf_list}" ] || die "deploy.json in $1 has no composeFiles"
	printf '%s\n' "${_cf_list}" | while IFS= read -r _cf_rel; do
		valid_compose_rel "${_cf_rel}" ||
			die "invalid composeFiles entry '${_cf_rel}' in $1/deploy.json (a relative path of A-Z a-z 0-9 . _ / -, without ..)"
		printf '%s\n' "${_cf_rel}"
	done || exit 1
}

sidecar_publish_files() {
	_tree="$1"
	_spf_files="$(sidecar_compose_files_checked "${_tree}")" || exit 1
	for _rel in ${_spf_files}; do
		_pub="$(echo "${_rel}" | sed 's/\.ya\?ml$/.publish.yml/')"
		[ -f "${_tree}/${_pub}" ] && echo "${_pub}"
		_pub2="$(echo "${_rel}" | sed 's/docker-compose\.ya\?ml$/docker-compose.publish.yml/')"
		[ "${_pub2}" != "${_pub}" ] && [ -f "${_tree}/${_pub2}" ] && echo "${_pub2}"
	done | sort -u
}

# Resolve sidecar image ref from limedoc.project.json (prints ref or empty).
sidecar_image_ref_from_tree() {
	_tree="$1"
	_proj="${_tree}/limedoc.project.json"
	[ -f "${_proj}" ] || return 0
	python3 - "${_proj}" <<'PY'
import json, sys
path = sys.argv[1]
with open(path, encoding="utf-8") as f:
    m = json.load(f)
tpl = (m.get("sidecar") or {}).get("imageTemplate") or ""
if not tpl:
    sys.exit(0)
ref = tpl.replace("{id}", m.get("id", "")).replace("{version}", m.get("version", ""))
if "oliver.maklott" in ref:
    print(f"legacy sidecar image owner in {path}: oliver.maklott", file=sys.stderr)
    sys.exit(2)
print(ref)
PY
}

# Export IMAGE_ENV=ref for compose when project metadata defines a sidecar image.
sidecar_image_env_exports() {
	_tree="$1"
	_id="$2"
	_ref="$(sidecar_image_ref_from_tree "${_tree}" 2>/dev/null || true)"
	[ -n "${_ref}" ] || return 0
	case "${_id}" in
		vectorsearch-lite) echo "VECTORSEARCH_IMAGE=${_ref}" ;;
		web-render) echo "WEB_RENDER_IMAGE=${_ref}" ;;
		*) _key="$(echo "${_id}" | tr 'a-z-' 'A-Z_')"; echo "${_key}_IMAGE=${_ref}" ;;
	esac
}

# Skip registry pull for local/dev image tags.
sidecar_should_pull_image() {
	_ref="$1"
	case "${_ref}" in
		*:local | limedoc-*:local) return 1 ;;
	esac
	case "${_ref}" in
		*/*) return 0 ;;
	esac
	return 1
}

sidecar_compose_pull() {
	# shellcheck disable=SC2086
	_args="$1"
	_img="$2"
	if [ -z "${_img}" ]; then
		docker compose ${_args} pull 2>/dev/null || true
		return 0
	fi
	if sidecar_should_pull_image "${_img}"; then
		step "pulling sidecar image ${_img}"
		if ! run_long "sidecar image pull" docker compose ${_args} pull; then
			if docker image inspect "${_img}" >/dev/null 2>&1; then
				info "pull failed — using local image ${_img}"
			else
				die "pull failed for ${_img} and no local image found"
			fi
		fi
	else
		info "skip pull for local/dev image tag (${_img})"
	fi
}

limedoc_image_for_configure() {
	_img="${LIMEDOC_IMAGE:-}"
	_envf="$(deploy_env_file 2>/dev/null || echo "${DEPLOY_DIR}/.env")"
	if [ -z "${_img}" ] && [ -f "${_envf}" ]; then
		_img="$(grep -E '^LIMEDOC_IMAGE=' "${_envf}" 2>/dev/null |
			head -1 | cut -d= -f2- | tr -d '\r' | tr -d '"' | tr -d "'")"
	fi
	echo "${_img}"
}

# Extra docker -v / -e so configure writes the same host env file as the app.
sidecar_configure_env_docker_args() {
	_envf="$(deploy_env_file)"
	case "${_envf}" in
		"${DEPLOY_DIR}"|"${DEPLOY_DIR}/"*)
			_rel="${_envf#"${DEPLOY_DIR}/"}"
			[ "${_rel}" = "${_envf}" ] && _rel=".env"
			echo "-e LIMEDOC_ENV_FILE=${_rel}"
			;;
		*)
			_env_dir="$(dirname "${_envf}")"
			_env_base="$(basename "${_envf}")"
			echo "-v ${_env_dir}:/limedoc-env:rw -e LIMEDOC_ENV_FILE=/limedoc-env/${_env_base}"
			;;
	esac
}

sidecar_run_configure() {
	_filter="$*"
	_force_noninteractive=""
	[ "${SIDECAR_CONFIGURE_NONINTERACTIVE:-}" = "1" ] &&
		_force_noninteractive="--non-interactive"
	_img="$(limedoc_image_for_configure)"
	[ -n "${_img}" ] || die "LIMEDOC_IMAGE required for sidecar configure"
	_tree_args=""
	_ids="$(printf '%s' "${_filter}" | tr ' ' '\n' | grep -v '^$' || true)"
	if [ -n "${_ids}" ]; then
		for _id in ${_ids}; do
			_ver="$(prod_packs_sidecars_json 2>/dev/null | FILTER="${_id}" python3 -c '
import json, os, sys
plan = json.load(sys.stdin)
want = os.environ.get("FILTER", "").strip()
for u in plan.get("units") or []:
    if u.get("pluginId") == want:
        print(u.get("version") or "unknown")
        break
' 2>/dev/null || echo unknown)"
			_tree="$(sidecar_resolve_tree "${_id}" "${_ver}")"
			_ctree="$(sidecar_tree_for_container "${_tree}")"
			_tree_args="${_tree_args} --tree ${_id}:${_ctree}"
		done
	else
		_json="$(prod_packs_sidecars_json 2>/dev/null || true)"
		if [ -n "${_json}" ]; then
			while IFS="$(printf '\t')" read -r _id _ver; do
				[ -n "${_id}" ] || continue
				_tree="$(sidecar_resolve_tree "${_id}" "${_ver}")"
				_ctree="$(sidecar_tree_for_container "${_tree}")"
				_tree_args="${_tree_args} --tree ${_id}:${_ctree}"
			done <<EOF
$(printf '%s' "${_json}" | python3 -c '
import json, sys
plan = json.load(sys.stdin)
for u in plan.get("units") or []:
    print((u.get("pluginId") or "") + "\t" + (u.get("version") or "unknown"))
')
EOF
		fi
	fi
	_id_args=""
	for _id in ${_filter}; do
		[ -n "${_id}" ] || continue
		_id_args="${_id_args} --id ${_id}"
	done
	# shellcheck disable=SC2086
	_run_it=""
	is_tty && _run_it="-it"
	_plugins_mount="$(sidecar_configure_mount_args)"
	_env_docker="$(sidecar_configure_env_docker_args)"
	docker run --rm ${_run_it} --network host \
		-v "${DEPLOY_DIR}:/deploy:rw" \
		${_plugins_mount} \
		${_env_docker} \
		-e LIMEDOC_HOST_DEPLOY=/deploy \
		"${_img}" \
		deno run --allow-env --allow-read --allow-write --allow-net \
		/app/scripts/sidecar_configure.ts \
		--deploy-dir /deploy ${_force_noninteractive} ${_id_args} ${_tree_args} ||
		die "sidecar configure failed"
	# Encrypted mode: worker keys (WEB_RENDER_SIDECAR_KEY, …) for the
	# configured sidecars; plaintext mode writes nothing.
	_key_ids="${_filter}"
	if [ -z "$(printf '%s' "${_key_ids}" | tr -d ' ')" ]; then
		# shellcheck disable=SC2086
		_key_ids="$(printf '%s\n' ${_tree_args} |
			sed -n 's/^\([a-z0-9-]*\):.*/\1/p' | tr '\n' ' ')"
	fi
	# shellcheck disable=SC2086
	sidecar_write_keys ${_key_ids} ||
		info "WARNING: could not write sidecar worker keys (see above); encrypted deployments need them before sidecar up"
}

# Image-side helper: /app/scripts/<script> in LIMEDOC_IMAGE with the deploy dir
# (and env file) mounted rw, no network. Same mount pattern as configure.
run_app_image_script() {
	_ais_script="$1"
	shift
	_ais_img="$(limedoc_image_for_configure)"
	[ -n "${_ais_img}" ] ||
		die "LIMEDOC_IMAGE required (deploy .env) to run ${_ais_script}"
	_ais_env="$(sidecar_configure_env_docker_args)"
	# shellcheck disable=SC2086
	docker run --rm --network none \
		-v "${DEPLOY_DIR}:/deploy:rw" \
		${_ais_env} \
		-e LIMEDOC_HOST_DEPLOY=/deploy \
		"${_ais_img}" \
		deno run --allow-env --allow-read --allow-write \
		"/app/scripts/${_ais_script}" --deploy-dir /deploy "$@"
}

# sidecar_write_keys <id…> — derive each worker's LIMEDOC_SIDECAR_KEY
# (sidecarKeyForEnv) inside the app image and merge it into the deploy .env.
# Ids without sidecar encryption are ignored; key material is never printed.
sidecar_write_keys() {
	_swk_args=""
	for _swk_id in "$@"; do
		case "${_swk_id}" in
			web-render|vectorsearch-lite) _swk_args="${_swk_args} --id ${_swk_id}" ;;
		esac
	done
	[ -n "${_swk_args}" ] || return 0
	# shellcheck disable=SC2086
	_swk_out="$(run_app_image_script sidecar_keys.ts ${_swk_args})" || return 1
	_swk_changed="$(printf '%s\n' "${_swk_out}" |
		sed -n 's/^LDCMD_SIDECAR_KEYS_CHANGED=//p')"
	[ -n "${_swk_changed}" ] &&
		info "wrote sidecar worker keys: ${_swk_changed} (recreate those sidecars)"
	return 0
}

sidecar_preflight() {
	_force="${1:-0}"
	_filter="$2"
	_img="$(limedoc_image_for_configure)"
	[ -n "${_img}" ] || {
		[ "${_force}" = "1" ] && return 0
		die "LIMEDOC_IMAGE required for sidecar preflight"
	}
	_tree_args=""
	_json="$(prod_packs_sidecars_json 2>/dev/null || true)"
	[ -n "${_json}" ] || {
		[ "${_force}" = "1" ] && return 0
		die "cannot read packs:sidecars for preflight"
	}
	_unit_count="$(printf '%s' "${_json}" | FILTER="${_filter}" python3 -c '
import json, os, sys
plan = json.load(sys.stdin)
raw = os.environ.get("FILTER", "").strip()
want = set(raw.split()) if raw else None
n = 0
for u in plan.get("units") or []:
    pid = u.get("pluginId") or ""
    if want is not None and pid not in want:
        continue
    n += 1
print(n)
' 2>/dev/null || echo 0)"
	if [ "${_unit_count}" = "0" ]; then
		return 0
	fi
	_tree_args=""
	while IFS="$(printf '\t')" read -r _id _ver; do
		[ -n "${_id}" ] || continue
		if [ -n "${_filter}" ]; then
			case " ${_filter} " in
				*" ${_id} "*) ;;
				*) continue ;;
			esac
		fi
		# A pack that cannot be fetched and verified (an old or unsigned
		# release, or one no longer in the registry) skips its sidecar
		# only; the running one, if any, is left alone.
		if _tree="$(sidecar_resolve_tree "${_id}" "${_ver}")" &&
			[ -n "${_tree}" ] &&
			_ctree="$(sidecar_tree_for_container "${_tree}")"; then
			_tree_args="${_tree_args} --tree ${_id}:${_ctree}"
		else
			SIDECAR_SKIP="${SIDECAR_SKIP:-} ${_id}@${_ver}"
			info "skipping sidecar ${_id}@${_ver}: its pack could not be fetched and verified"
		fi
	done <<EOF
$(printf '%s' "${_json}" | FILTER="${_filter}" python3 -c '
import json, os, sys
plan = json.load(sys.stdin)
raw = os.environ.get("FILTER", "").strip()
want = set(raw.split()) if raw else None
for u in plan.get("units") or []:
    pid = u.get("pluginId") or ""
    if want is not None and pid not in want:
        continue
    print(pid + "\t" + (u.get("version") or "unknown"))
')
EOF
	if [ -z "${_tree_args}" ]; then
		return 0
	fi
	# shellcheck disable=SC2086
	_plugins_mount="$(sidecar_configure_mount_args)"
	_env_docker="$(sidecar_configure_env_docker_args)"
	_pf_out="$(mktemp)"
	_pf_st=0
	docker run --rm --network host \
		-v "${DEPLOY_DIR}:/deploy:ro" \
		${_plugins_mount} \
		${_env_docker} \
		-e LIMEDOC_HOST_DEPLOY=/deploy \
		"${_img}" \
		deno run --allow-env --allow-read --allow-net \
		/app/scripts/sidecar_configure.ts \
		--deploy-dir /deploy --non-interactive ${_tree_args} \
		>"${_pf_out}" 2>&1 || _pf_st=$?
	# A busy port that one of this instance's own containers publishes is
	# the sidecar about to be recreated, not a conflict.
	_own_ports=" $(instance_own_host_ports) "
	while IFS= read -r _pf_line; do
		_pf_port="$(printf '%s' "${_pf_line}" | sed -n 's/.*=\([0-9][0-9]*\) busy for .*/\1/p')"
		if [ -n "${_pf_port}" ] && case "${_own_ports}" in *" ${_pf_port} "*) true ;; *) false ;; esac; then
			printf '%s\n' "${_pf_line%% busy for *} is held by this instance's own running sidecar (fine: it is recreated)"
		else
			printf '%s\n' "${_pf_line}"
		fi
	done <"${_pf_out}"
	rm -f "${_pf_out}"
	if [ "${_pf_st}" -ne 0 ]; then
		[ "${_force}" = "1" ] && return 0
		die "sidecar preflight failed — run: ldcmd sidecar configure"
	fi
}

# sidecar_sync_image_env <envfile> <KEY=pack image ref>: keep the sidecar
# image in the deploy .env on the pack's version. A value of the same
# repository (seeded by an earlier ldcmd) follows the pack; another
# repository or a digest is an operator override and stays. Prints the
# image compose will use.
sidecar_sync_image_env() {
	_si_envf="$1"
	_si_key="${2%%=*}"
	_si_ref="${2#*=}"
	_si_cur="$(grep -E "^${_si_key}=" "${_si_envf}" 2>/dev/null | tail -1 |
		cut -d= -f2- | tr -d "\r\"'")"
	if [ -z "${_si_cur}" ]; then
		if grep -qE "^${_si_key}=" "${_si_envf}" 2>/dev/null; then
			sidecar_set_env_line "${_si_envf}" "${_si_key}" "${_si_ref}"
		else
			printf '%s=%s\n' "${_si_key}" "${_si_ref}" >> "${_si_envf}"
		fi
		info "set ${_si_key}=${_si_ref} in ${_si_envf}"
	elif [ "${_si_cur}" = "${_si_ref}" ]; then
		:
	elif case "${_si_cur}" in *@*) false ;; *) true ;; esac &&
		[ "${_si_cur%:*}" = "${_si_ref%:*}" ]; then
		sidecar_set_env_line "${_si_envf}" "${_si_key}" "${_si_ref}"
		info "${_si_key}: ${_si_cur##*:} → ${_si_ref##*:} (follows the pack version) in ${_si_envf}"
	else
		info "using ${_si_key}=${_si_cur} from ${_si_envf} (operator override; the pack's image is ${_si_ref})"
		_si_ref="${_si_cur}"
	fi
	printf '%s\n' "${_si_ref}"
}

# sidecar_set_env_line <envfile> <key> <value>: replace the key's line(s)
# in place (same inode, so owner and mode stay).
sidecar_set_env_line() {
	_sl_tmp="$(umask 077 && mktemp)" || die "mktemp failed"
	# Key and value through the environment: awk -v would read backslash
	# escapes in them.
	LD_K="$2" LD_V="$3" awk 'BEGIN { k = ENVIRON["LD_K"]; v = ENVIRON["LD_V"] }
		index($0, k "=") == 1 { print k "=" v; next } { print }' \
		"$1" >"${_sl_tmp}" && cat "${_sl_tmp}" >"$1"
	rm -f "${_sl_tmp}"
}

# Host ports published by this instance's own containers (app, redis and
# its sidecars), space-separated.
instance_own_host_ports() {
	_op_proj="$(prod_compose_project_name)"
	docker ps --format '{{.Label "com.docker.compose.project"}}	{{.Ports}}' 2>/dev/null |
		awk -F'\t' -v p="${_op_proj}" '$1 == p || index($1, p "-sidecar-") == 1 { print $2 }' |
		grep -oE ':[0-9]+->' | sed 's/[^0-9]//g' | sort -u | xargs
}

# Sets _tree, _proj, _envf, _mode and _args (compose args) for one sidecar.
sidecar_compose_args() {
	_id="$1"
	_ver="$2"
	_tree="$(sidecar_resolve_tree "${_id}" "${_ver}")"
	_proj="$(sidecar_compose_project_name "${_id}")"
	_envf="$(deploy_env_file)"
	_mode="$(grep -E '^DEPLOY_NETWORK_MODE=' "${_envf}" 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true)"
	# Resolve relative host binds (e.g. ./data/cache/vectorsearch) against deploy dir.
	_args="--project-directory ${DEPLOY_DIR} --project-name ${_proj} --env-file ${_envf}"
	# Relative compose paths resolve against DEPLOY_DIR; a pack mounts its own
	# files (scripts, configs) through ${SIDECAR_PACK_DIR} (absolute).
	SIDECAR_PACK_DIR="$(CDPATH="" cd -- "${_tree}" && pwd)"
	export SIDECAR_PACK_DIR
	require_plain_path "sidecar pack tree" "${_tree}"
	_sca_files="$(sidecar_compose_files_checked "${_tree}")" || exit 1
	for _rel in ${_sca_files}; do
		_args="${_args} -f ${_tree}/${_rel}"
	done
	if [ "${_mode}" = "external" ]; then
		for _pub in $(sidecar_publish_files "${_tree}"); do
			_args="${_args} -f ${_tree}/${_pub}"
		done
	fi
}

# deploy.json commands[<name>] → "service<TAB>arg<TAB>arg…" (exit 2: unknown).
sidecar_deploy_command() {
	python3 - "$1/deploy.json" "$2" <<'PY'
import json, re, sys
m = json.load(open(sys.argv[1], encoding="utf-8"))
name = sys.argv[2]
cmds = m.get("commands") or {}
c = cmds.get(name)
if not isinstance(c, dict):
    known = " ".join(sorted(cmds)) or "(none)"
    print(known)
    sys.exit(2)
svc = c.get("service") or ""
args = c.get("args") or []
if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$", svc) or \
        not all(isinstance(a, str) and "\t" not in a and "\n" not in a for a in args):
    print("invalid command definition")
    sys.exit(3)
print("\t".join([svc] + args))
PY
}

sidecar_up_one() {
	sidecar_compose_args "$1" "$2"
	_img_ref="$(sidecar_image_ref_from_tree "${_tree}" 2>/dev/null || true)"
	_img_env="$(sidecar_image_env_exports "${_tree}" "${_id}" 2>/dev/null || true)"
	if [ -n "${_img_env}" ]; then
		_img_ref="$(sidecar_sync_image_env "${_envf}" "${_img_env}")"
	fi
	step "sidecar ${_id}@${_ver} (project ${_proj})"
	sidecar_compose_pull "${_args}" "${_img_ref}"
	# shellcheck disable=SC2086
	run_long "sidecar ${_id} up" docker compose ${_args} up -d ||
		die "sidecar compose up failed: ${_id}"
	echo "${_id}|${_ver}|${_proj}"
}

cmd_sidecar_status() {
	resolve_prod_deploy_dir
	info "installed sidecars (from app):"
	prod_packs_sidecars_json || info "(app not running or packs:sidecars failed)"
	if [ -f "$(sidecar_active_path)" ]; then
		info "active host projects:"
		cat "$(sidecar_active_path)"
	else
		info "no sidecars/active.json yet"
	fi
}

cmd_sidecar_configure() {
	resolve_prod_deploy_dir
	sidecar_run_configure "$@"
}

cmd_sidecar_up() {
	resolve_prod_deploy_dir
	command -v python3 >/dev/null 2>&1 || die "python3 required for sidecar up"
	command -v curl >/dev/null 2>&1 || die "curl required"
	command -v unzip >/dev/null 2>&1 || die "unzip required"
	_force=0
	_configure=0
	_filter=""
	while [ $# -gt 0 ]; do
		case "$1" in
			--force) _force=1; shift ;;
			--configure) _configure=1; shift ;;
			*) _filter="${_filter} $1"; shift ;;
		esac
	done
	_filter="$(echo "${_filter}" | xargs)"
	if [ "${_configure}" = "1" ]; then
		sidecar_run_configure ${_filter}
	fi
	_su_missing="$(redis_secure_missing)"
	[ -z "${_su_missing}" ] ||
		info "Redis auth not set up (${_su_missing}); web-render / vectorsearch-lite need it: ldcmd redis secure"
	SIDECAR_SKIP=""
	sidecar_preflight "${_force}" "${_filter}"
	_json="$(prod_packs_sidecars_json)" || die "cannot read packs:sidecars (is app up?)"
	_ids="$(printf '%s' "${_json}" | FILTER="${_filter}" python3 -c '
import json, os, sys
plan = json.load(sys.stdin)
raw = os.environ.get("FILTER", "").strip()
want = set(raw.split()) if raw else None
for u in plan.get("units") or []:
	pid = u.get("pluginId") or ""
	if want is not None and pid not in want:
		continue
	print(pid + "\t" + (u.get("version") or "unknown"))
')"
	[ -n "${_ids}" ] || {
		info "no sidecar units to start"
		return 0
	}
	# Redirect below opens before the loop body; ensure dir exists first.
	mkdir -p "${DEPLOY_DIR}/sidecars"
	# shellcheck disable=SC2039
	_failed_file="${DEPLOY_DIR}/sidecars/.failed"
	: > "${_failed_file}"
	echo "${_ids}" | while IFS="$(printf '\t')" read -r _id _ver; do
		[ -n "${_id}" ] || continue
		case " ${SIDECAR_SKIP} " in
			*" ${_id}@${_ver} "*) continue ;;
		esac
		# Subshell: one sidecar failing must not stop the others.
		if (sidecar_up_one "${_id}" "${_ver}") >/dev/null; then
			printf '%s %s %s ' "${_id}" "${_ver}" "$(sidecar_compose_project_name "${_id}")"
		else
			printf '%s@%s\n' "${_id}" "${_ver}" >> "${_failed_file}"
		fi
	done > "${DEPLOY_DIR}/sidecars/.active_rebuild"
	_failed="$(xargs < "${_failed_file}")"
	rm -f "${_failed_file}"
	_active_mode="replace"
	# Keep the records of sidecars that were not (re)started.
	if [ -n "${_filter}" ] || [ -n "${SIDECAR_SKIP}${_failed}" ]; then
		_active_mode="merge"
	fi
	# shellcheck disable=SC2046
	sidecar_update_active "${_active_mode}" \
		$(cat "${DEPLOY_DIR}/sidecars/.active_rebuild" 2>/dev/null || true)
	rm -f "${DEPLOY_DIR}/sidecars/.active_rebuild"
	_not="$(echo "${SIDECAR_SKIP} ${_failed}" | xargs)"
	if [ -n "${_not}" ]; then
		info "sidecars NOT started: ${_not}"
		if [ -n "${SIDECAR_SKIP}" ]; then
			_skip_ids="$(printf '%s\n' ${SIDECAR_SKIP} | sed 's/@.*//' | xargs)"
			info "  their installed pack versions cannot be fetched and verified (older or unsigned"
			info "  releases); a container already running from them keeps running. Update the packs,"
			info "  which also starts their sidecars: ldcmd plugin update ${_skip_ids}"
		fi
		[ -z "${_failed}" ] ||
			info "  failed to start: ${_failed} (see above; retry: ldcmd sidecar up)"
		return 3
	fi
	info "sidecar up complete"
	if echo "${_ids}" | grep -q '^collabora[[:space:]]'; then
		info "Collabora: COLLABORA_SSL_TERMINATION=true (HTTPS public) so the editor uses wss://; recreate after changing it"
		info "Collabora: WOPI_APP_BASE_URL should be public APP_BASE (aliasgroup3), not host.docker.internal"
		info "Collabora: distroless — no coolconfig exec; ensure /etc/coolwsd volume has proof_key, or keep COLLABORA_VALIDATE_PROOF_KEY=false until discovery shows proof-key"
	fi
}

# ldcmd sidecar run <id> <command> [-- args…]: one-shot pack command from
# deploy.json `commands` (docker compose run --rm, same env/network as up).
cmd_sidecar_run() {
	resolve_prod_deploy_dir
	command -v python3 >/dev/null 2>&1 || die "python3 required for sidecar run"
	_rid="${1:-}"
	_rcmd="${2:-}"
	[ -n "${_rid}" ] && [ -n "${_rcmd}" ] ||
		die "usage: ldcmd sidecar run <plugin-id> <command> [-- args…]"
	shift 2
	[ "${1:-}" = "--" ] && shift
	_json="$(prod_packs_sidecars_json)" || die "cannot read packs:sidecars (is app up?)"
	_rver="$(printf '%s' "${_json}" | RID="${_rid}" python3 -c '
import json, os, sys
for u in json.load(sys.stdin).get("units") or []:
	if u.get("pluginId") == os.environ["RID"]:
		print(u.get("version") or "unknown")
		break
')"
	[ -n "${_rver}" ] || die "sidecar run: ${_rid} is not an installed sidecar pack"
	sidecar_compose_args "${_rid}" "${_rver}"
	_spec="$(sidecar_deploy_command "${_tree}" "${_rcmd}")" || {
		_rc=$?
		[ "${_rc}" = "2" ] &&
			die "sidecar run: ${_rid}@${_rver} declares no command '${_rcmd}' (available: ${_spec})"
		die "sidecar run: ${_rid} command '${_rcmd}': ${_spec}"
	}
	_svc="$(printf '%s' "${_spec}" | cut -f1)"
	step "sidecar ${_rid}@${_rver}: ${_rcmd} (service ${_svc})"
	# Fixed args from deploy.json (tab separated, no shell parsing), then the
	# operator's extra args.
	_tab="$(printf '\t')"
	_old_ifs="${IFS}"
	# Split at tabs only, without pathname expansion: an argument such as *
	# stays what the pack wrote.
	case "$-" in
		*f*) _had_noglob=1 ;;
		*) _had_noglob=0 ;;
	esac
	set -f
	IFS="${_tab}"
	# shellcheck disable=SC2086
	set -- ${_spec} "$@"
	IFS="${_old_ifs}"
	[ "${_had_noglob}" = "1" ] || set +f
	shift # service
	# shellcheck disable=SC2086
	docker compose ${_args} run --rm "${_svc}" "$@"
}

# ldcmd sidecar upgrade <id> [args…] = sidecar run <id> upgrade -- args…
cmd_sidecar_upgrade() {
	_uid="${1:-}"
	[ -n "${_uid}" ] || die "usage: ldcmd sidecar upgrade <plugin-id> [args…]"
	shift
	[ "${1:-}" = "--" ] && shift
	cmd_sidecar_run "${_uid}" upgrade -- "$@"
}

cmd_sidecar_down() {
	resolve_prod_deploy_dir
	_filter="$(echo "$*" | xargs)"
	_projs=""
	_core_proj="$(prod_compose_project_name)"
	if [ -f "$(sidecar_active_path)" ] && command -v python3 >/dev/null 2>&1; then
		_projs="$(FILTER="${_filter}" CORE_PROJ="${_core_proj}" python3 - "$(sidecar_active_path)" <<'PY'
import json, os, sys
data = json.load(open(sys.argv[1], encoding="utf-8"))
raw = os.environ.get("FILTER", "").strip()
want = set(raw.split()) if raw else None
core = os.environ.get("CORE_PROJ") or "limedoc"
for p in data.get("projects") or []:
	pid = p.get("id") or ""
	if want is not None and pid not in want:
		continue
	print(p.get("project") or (f"{core}-sidecar-{pid}"))
PY
)"
	fi
	if [ -z "${_filter}" ]; then
		_json="$(prod_packs_sidecars_json 2>/dev/null || true)"
		if [ -n "${_json}" ] && command -v python3 >/dev/null 2>&1; then
			_from_plan="$(printf '%s' "${_json}" | CORE_PROJ="${_core_proj}" python3 -c '
import json, os, sys
plan = json.load(sys.stdin)
core = os.environ.get("CORE_PROJ") or "limedoc"
for u in plan.get("units") or []:
    pid = u.get("pluginId") or ""
    if pid:
        print(f"{core}-sidecar-{pid}")
' 2>/dev/null || true)"
			_projs="${_projs} ${_from_plan}"
		fi
	fi
	# Filtered downs use active.json only — do not invent {proj}-sidecar-$id
	# for packs that never declared / never started a sidecar.
	_projs="$(printf '%s\n' ${_projs} | grep -v '^$' | sort -u || true)"
	if [ -z "${_projs}" ]; then
		info "no sidecar projects to stop"
		return 0
	fi
	for _proj in ${_projs}; do
		[ -n "${_proj}" ] || continue
		info "sidecar down project ${_proj}"
		docker compose --project-name "${_proj}" down || true
	done
	if command -v python3 >/dev/null 2>&1; then
		if [ -z "${_filter}" ]; then
			sidecar_update_active replace
		else
			# shellcheck disable=SC2086
			sidecar_update_active remove ${_filter}
		fi
	fi
	info "sidecar down complete"
}

# ── sidecar isolate (web-render) ──────────────────────────────────────────────
#
# Guided hardening for the web-render worker (plugin README "Isolation"):
#   1. Redis auth that survives restarts: ACL file (--aclfile via REDIS_ARGS),
#      a password for the app user, a `web-render` user limited to render keys
#   2. own Docker network {basename}_render; redis + app join it through
#      the ISOLATION_OVERLAY_FILE compose overlay (which also carries
#      REDIS_ARGS + a NOAUTH-tolerant healthcheck for older deploy compose files)
#   3. worker env: WEB_RENDER_REDIS_URL, optional egress proxy / resolver rules
#      (Chromium settings; the network is a boundary only with
#      --internal-network)
#   4. encrypted mode: WEB_RENDER_SIDECAR_KEY
#   5. restart redis → app → worker, then verify
# The deploy-side files come from /app/scripts/web_render_isolate.ts in the app
# image. Passwords are read from .env and reach redis-cli on stdin only.

isolate_compose() {
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} "$@"
}

# redis_url_password <url> / redis_url_user <url> — userinfo parts (URL-safe
# values only; ldcmd isolate never writes percent-encoded ones).
redis_url_password() {
	_rup="${1#*://}"
	case "${_rup}" in
		*@*) _rup="${_rup%@*}" ;;
		*) return 0 ;;
	esac
	case "${_rup}" in
		*:*) printf '%s\n' "${_rup#*:}" ;;
	esac
}

redis_url_user() {
	_ruu="${1#*://}"
	case "${_ruu}" in
		*@*) _ruu="${_ruu%@*}" ;;
		*) return 0 ;;
	esac
	printf '%s\n' "${_ruu%%:*}"
}

# redis_cli_as <user> <password> — run redis-cli in the redis service with
# commands on stdin. The AUTH line (if any) is prepended on stdin, so the
# password never appears in a process argument list.
redis_cli_as() {
	_rca_user="$1"
	_rca_pw="$2"
	{
		if [ -n "${_rca_pw}" ]; then
			if [ -z "${_rca_user}" ] || [ "${_rca_user}" = "default" ]; then
				printf 'AUTH %s\n' "${_rca_pw}"
			else
				printf 'AUTH %s %s\n' "${_rca_user}" "${_rca_pw}"
			fi
		fi
		cat
	} | isolate_compose exec -T redis redis-cli 2>&1 | tr -d '\r'
}

# ask_yes_no <question> <default y|n> — 0 = yes. Only called on a TTY.
ask_yes_no() {
	_ayn_def="$2"
	if [ "${_ayn_def}" = "y" ]; then
		printf '%s [Y/n]: ' "$1" >&2
	else
		printf '%s [y/N]: ' "$1" >&2
	fi
	_ayn=""
	read -r _ayn || _ayn=""
	case "${_ayn:-${_ayn_def}}" in
		y|Y|yes|YES|Yes) return 0 ;;
		*) return 1 ;;
	esac
}

# ask_value <var> <question> <current> — empty answer keeps current,
# "none" clears it.
ask_value() {
	_av_var="$1"
	printf '%s [%s]: ' "$2" "${3:-none}" >&2
	_av=""
	read -r _av || _av=""
	case "${_av}" in
		"") _av="$3" ;;
		none|NONE|-) _av="" ;;
	esac
	eval "${_av_var}=\${_av}"
}

isolate_step() {
	printf '\n%s\n' "$*" >&2
}

isolate_say() {
	printf '  %s\n' "$*" >&2
}

isolate_check() {
	if [ "$1" = "0" ]; then
		printf '  ok    %s\n' "$2" >&2
	else
		printf '  FAIL  %s\n' "$2" >&2
		_iso_fails=$((_iso_fails + 1))
	fi
}

# A finding that is reported, not counted as a failed check.
isolate_note() {
	printf '  note  %s\n' "$*" >&2
}

# "true" when the Docker network exists and was created with --internal.
network_is_internal() {
	[ "$(docker network inspect -f '{{.Internal}}' "$1" 2>/dev/null || true)" = "true" ]
}

# isolate_egress_report <render network>: says whether the render network has
# a route to outside addresses. Reported only: a plain bridge is a supported
# setup (external renders need it, or a proxy attached to the network).
# LDCMD_EGRESS_PROBE=0 skips the probe; LDCMD_EGRESS_PROBE_URL sets its target.
isolate_egress_report() {
	_ie_net="$1"
	if network_is_internal "${_ie_net}"; then
		isolate_check 0 "render network ${_ie_net} is internal: no route to outside addresses"
		return 0
	fi
	if [ "${LDCMD_EGRESS_PROBE:-1}" = "0" ]; then
		isolate_note "render network ${_ie_net} is a plain bridge; egress probe skipped (LDCMD_EGRESS_PROBE=0)"
		return 0
	fi
	_ie_url="${LDCMD_EGRESS_PROBE_URL:-http://example.com/}"
	if docker run --rm --network "${_ie_net}" "${LDCMD_HELPER_IMAGE}" \
		wget -q -T 5 -O /dev/null "${_ie_url}" >/dev/null 2>&1; then
		isolate_note "render network ${_ie_net} has a route out: a container on it fetched ${_ie_url}."
		isolate_note "The network keeps the worker away from the other containers, not from the"
		isolate_note "internet, the LAN or the host. Outbound requests are limited only inside the"
		isolate_note "worker (its request filter, RENDER_PROXY_SERVER, RENDER_HOST_RESOLVER_RULES),"
		isolate_note "which a compromised renderer need not honour. Block renders only, or a proxy"
		isolate_note "attached to this network: set it up again with --internal-network (help)."
	else
		isolate_note "render network ${_ie_net} is a plain bridge; a probe container on it could not fetch"
		isolate_note "${_ie_url} (no route out, or the probe image ${LDCMD_HELPER_IMAGE} could not run): not conclusive."
	fi
}

# Tunables for slow hosts / tests.
isolate_wait_tries() { echo "${LDCMD_ISOLATE_WAIT_TRIES:-20}"; }
isolate_wait_sec() { echo "${LDCMD_ISOLATE_WAIT_SEC:-3}"; }

# isolate_verify — checks after apply (or `--verify`). Returns failure count.
isolate_verify() {
	_iso_fails=0
	_iv_url="$(deploy_env_get REDIS_URL)"
	_iv_user="$(redis_url_user "${_iv_url}")"
	_iv_pw="$(redis_url_password "${_iv_url}")"
	_iv_wpw="$(redis_url_password "$(deploy_env_get WEB_RENDER_REDIS_URL)")"
	_iv_hb="$(deploy_env_get RENDER_HEARTBEAT_KEY)"
	_iv_hb="${_iv_hb:-render:heartbeat}"
	_iv_mode="$(deploy_env_get DEPLOY_NETWORK_MODE)"
	_iv_net="$(deploy_env_get WEB_RENDER_NETWORK_NAME)"

	isolate_step "Verify"
	_iv_out="$(printf 'PING\n' | redis_cli_as "" "")"
	case "${_iv_out}" in
		*NOAUTH*) isolate_check 0 "Redis refuses the default user without a password" ;;
		*) isolate_check 1 "Redis refuses the default user without a password (got: ${_iv_out})" ;;
	esac
	_iv_out="$(printf 'PING\n' | redis_cli_as "${_iv_user}" "${_iv_pw}")"
	case "${_iv_out}" in
		*PONG*) isolate_check 0 "app credentials (REDIS_URL) are accepted" ;;
		*) isolate_check 1 "app credentials (REDIS_URL) are accepted" ;;
	esac
	if [ -z "${_iv_wpw}" ]; then
		isolate_check 1 "WEB_RENDER_REDIS_URL is set in .env"
	else
		_iv_out="$(printf 'GET sessions:x\n' | redis_cli_as web-render "${_iv_wpw}")"
		case "${_iv_out}" in
			*NOPERM*) isolate_check 0 "worker user cannot read app keys (GET sessions:x → NOPERM)" ;;
			*) isolate_check 1 "worker user cannot read app keys (GET sessions:x → NOPERM)" ;;
		esac
		_iv_out="$(printf 'GET %s\n' "${_iv_hb}" | redis_cli_as web-render "${_iv_wpw}")"
		case "${_iv_out}" in
			*NOPERM*|*WRONGPASS*|*NOAUTH*|*"Could not connect"*)
				isolate_check 1 "worker user can read its own keys (GET ${_iv_hb})" ;;
			*) isolate_check 0 "worker user can read its own keys (GET ${_iv_hb})" ;;
		esac
	fi
	_iv_aclf="$(printf 'CONFIG GET aclfile\n' | redis_cli_as "${_iv_user}" "${_iv_pw}" |
		sed -n '/^aclfile$/{n;p;}' | head -1)"
	if [ -n "${_iv_aclf}" ]; then
		isolate_check 0 "Redis loads users from ${_iv_aclf} (survives restarts)"
	else
		isolate_check 1 "Redis runs with --aclfile (users would be lost on restart)"
	fi
	_iv_i=0
	_iv_hb_ok=1
	while [ "${_iv_i}" -lt "$(isolate_wait_tries)" ]; do
		_iv_out="$(printf 'EXISTS %s\n' "${_iv_hb}" | redis_cli_as "${_iv_user}" "${_iv_pw}" | tail -1)"
		if [ "${_iv_out}" = "1" ]; then
			_iv_hb_ok=0
			break
		fi
		_iv_i=$((_iv_i + 1))
		[ "${_iv_i}" -lt "$(isolate_wait_tries)" ] && sleep "$(isolate_wait_sec)"
	done
	isolate_check "${_iv_hb_ok}" "worker heartbeat ${_iv_hb} is present"
	# A worker compose that predates WEB_RENDER_REDIS_URL still connects with
	# the app credentials: everything works, nothing is isolated.
	if printf 'CLIENT LIST\n' | redis_cli_as "${_iv_user}" "${_iv_pw}" |
		grep -q 'user=web-render '; then
		isolate_check 0 "the worker connects as the web-render user"
	else
		isolate_check 1 "the worker connects as the web-render user (update the web-render pack if its compose ignores WEB_RENDER_REDIS_URL)"
	fi
	if [ "${_iv_mode}" != "external" ] && [ -n "${_iv_net}" ]; then
		if isolate_compose exec -T app deno eval \
			"const r=await fetch('http://web-render-worker:8092/').catch(()=>null);Deno.exit(r&&r.ok?0:1)" \
			>/dev/null 2>&1; then
			isolate_check 0 "app reaches the worker health port over ${_iv_net}"
		else
			isolate_check 1 "app reaches the worker health port over ${_iv_net}"
		fi
		isolate_egress_report "${_iv_net}"
	fi
	if docker compose --project-name "$(sidecar_compose_project_name web-render)" \
		logs --tail 200 2>/dev/null | grep -q NOPERM; then
		isolate_check 1 "worker logs show no NOPERM (ACL too tight: report the command)"
	else
		isolate_check 0 "worker logs show no NOPERM"
	fi
	return "${_iso_fails}"
}

isolate_usage() {
	help_text sidecar isolate >&2
}

cmd_sidecar_isolate() {
	_iso_target="${1:-}"
	[ $# -gt 0 ] && shift
	case "${_iso_target}" in
		web-render) ;;
		""|-h|--help) isolate_usage; [ -n "${_iso_target}" ] && return 0; exit 2 ;;
		*) die "sidecar isolate: only web-render is supported (got '${_iso_target}')" ;;
	esac
	_iso_yes="${LDCMD_ASSUME_YES:-0}"
	_iso_verify_only=0
	_iso_rotate=0
	_iso_restart=1
	_iso_proxy_set=0
	_iso_proxy=""
	_iso_rules_set=0
	_iso_rules=""
	_iso_net=""
	_iso_internal=0
	while [ $# -gt 0 ]; do
		case "$1" in
			-y|--yes) _iso_yes=1; shift ;;
			--verify) _iso_verify_only=1; shift ;;
			--rotate-worker-password) _iso_rotate=1; shift ;;
			--no-restart) _iso_restart=0; shift ;;
			--proxy-server)
				[ $# -ge 2 ] || die "--proxy-server requires a value"
				_iso_proxy_set=1; _iso_proxy="$2"; shift 2 ;;
			--resolver-rules)
				[ $# -ge 2 ] || die "--resolver-rules requires a value"
				_iso_rules_set=1; _iso_rules="$2"; shift 2 ;;
			--network-name)
				[ $# -ge 2 ] || die "--network-name requires a value"
				_iso_net="$2"; shift 2 ;;
			--internal-network) _iso_internal=1; shift ;;
			-h|--help) isolate_usage; return 0 ;;
			*) isolate_usage; die "sidecar isolate: unknown option $1" ;;
		esac
	done
	_iso_interactive=0
	if [ "${_iso_yes}" != "1" ] && [ "${_iso_verify_only}" != "1" ]; then
		is_tty ||
			die "sidecar isolate: no TTY to ask on; re-run with --yes (and options) to apply non-interactively"
		_iso_interactive=1
	fi

	resolve_prod_deploy_dir
	prod_core_compose_args
	command -v docker >/dev/null 2>&1 || die "docker is required"
	isolate_compose ps -q redis 2>/dev/null | grep -q . ||
		die "redis is not running in ${DEPLOY_DIR} (start it with: ldcmd up)"

	if [ "${_iso_verify_only}" = "1" ]; then
		isolate_verify && { info "isolation checks passed"; return 0; }
		die "isolation checks failed (re-run: ldcmd sidecar isolate web-render)"
	fi

	_iso_mode="$(deploy_env_get DEPLOY_NETWORK_MODE)"
	[ "${_iso_mode}" = "external" ] || _iso_mode="internal"
	_iso_proj="$(prod_compose_project_name)"
	[ -n "${_iso_net}" ] || _iso_net="$(deploy_env_get WEB_RENDER_NETWORK_NAME)"
	[ -n "${_iso_net}" ] || _iso_net="${_iso_proj}_render"
	_iso_old_url="$(deploy_env_get REDIS_URL)"
	_iso_old_user="$(redis_url_user "${_iso_old_url}")"
	_iso_old_pw="$(redis_url_password "${_iso_old_url}")"

	# ── current state ──
	_iso_state="$(printf 'INFO server\nCONFIG GET aclfile\nACL USERS\n' |
		redis_cli_as "${_iso_old_user}" "${_iso_old_pw}")"
	case "${_iso_state}" in
		*NOAUTH*|*WRONGPASS*)
			die "Redis rejects the credentials in REDIS_URL (${DEPLOY_DIR}/.env); fix REDIS_URL first" ;;
	esac
	_iso_ver="$(printf '%s\n' "${_iso_state}" | sed -n 's/^redis_version:\(.*\)$/\1/p' | head -1)"
	_iso_aclfile="$(printf '%s\n' "${_iso_state}" | sed -n '/^aclfile$/{n;p;}' | head -1)"
	case "${_iso_ver}" in
		[0-6].*|"") die "Redis ${_iso_ver:-?} is too old: key-scoped ACL users need Redis 7+ (set REDIS_IMAGE)" ;;
	esac
	if [ -z "${_iso_aclfile}" ] &&
		! isolate_compose exec -T redis sh -c \
			'grep -qs REDIS_ARGS /entrypoint.sh /usr/local/bin/docker-entrypoint.sh' \
			>/dev/null 2>&1; then
		die "REDIS_IMAGE does not honour REDIS_ARGS (redis-stack does). Start redis with '--aclfile /data/users.acl' (compose command override, file must exist), then re-run"
	fi
	_iso_has_worker=0
	printf '%s\n' "${_iso_state}" | grep -qx 'web-render' && _iso_has_worker=1
	_iso_net_exists=0
	if [ "${_iso_mode}" = "internal" ] &&
		docker network inspect "${_iso_net}" >/dev/null 2>&1; then
		_iso_net_exists=1
	fi
	if [ "${_iso_internal}" = "1" ]; then
		[ "${_iso_mode}" = "internal" ] ||
			die "--internal-network needs the shared-network mode (DEPLOY_NETWORK_MODE=external has no render network)"
		if [ "${_iso_net_exists}" = "1" ] && ! network_is_internal "${_iso_net}"; then
			die "network ${_iso_net} exists and is not internal; Docker cannot change that in place. Undo the network step (rm ${DEPLOY_DIR}/${ISOLATION_OVERLAY_FILE}; delete WEB_RENDER_NETWORK_NAME from .env; ldcmd up; ldcmd sidecar down web-render; docker network rm ${_iso_net}), then re-run with --internal-network"
		fi
	fi
	_iso_cur_proxy="$(deploy_env_get RENDER_PROXY_SERVER)"
	_iso_cur_rules="$(deploy_env_get RENDER_HOST_RESOLVER_RULES)"

	printf 'Web-render worker isolation for %s (Redis %s, %s mode)\n' \
		"${DEPLOY_DIR}" "${_iso_ver}" "${_iso_mode}" >&2
	isolate_step "1. Redis auth that survives restarts"
	isolate_say "The worker runs untrusted page content in Chromium. Today it can use any"
	isolate_say "Redis user the app can. ldcmd writes an ACL file into the Redis volume"
	isolate_say "(hashed passwords only), gives the app user a password (REDIS_URL) and"
	isolate_say "adds a 'web-render' user limited to render:* plus read-only ctx:*/res:*."
	if [ -n "${_iso_aclfile}" ]; then
		isolate_say "state: Redis already loads ${_iso_aclfile}"
	else
		isolate_say "state: no ACL file; REDIS_ARGS gets '--aclfile /data/users.acl' (Redis restart)"
	fi
	if [ -n "${_iso_old_pw}" ]; then
		isolate_say "state: REDIS_URL has a password (kept)"
	else
		isolate_say "state: REDIS_URL has no password; one is generated. External Redis"
		isolate_say "       clients (monitoring, scripts) need the new REDIS_URL afterwards."
	fi
	if [ "${_iso_has_worker}" = "1" ]; then
		isolate_say "state: web-render user exists (password kept unless rotated)"
	fi
	isolate_step "2. Own Docker network"
	if [ "${_iso_mode}" = "internal" ]; then
		isolate_say "The worker leaves the shared app network and joins ${_iso_net}; redis"
		isolate_say "and app join it too (compose overlay ${ISOLATION_OVERLAY_FILE}) so"
		isolate_say "the health URL http://web-render-worker:8092 keeps working."
		if [ "${_iso_internal}" = "1" ]; then
			isolate_say "--internal-network: the network has no route out. The worker reaches"
			isolate_say "Redis and the app only; external renders need a proxy attached to"
			isolate_say "${_iso_net} (RENDER_PROXY_SERVER) or stop working."
		else
			isolate_say "This keeps the worker away from the other containers (Collabora, search"
			isolate_say "worker, …). It is a plain bridge: outbound connections (internet, LAN,"
			isolate_say "host) are NOT restricted by it. --internal-network removes the route out."
		fi
		if [ "${_iso_net_exists}" = "1" ]; then
			isolate_say "state: network ${_iso_net} exists"
		else
			isolate_say "state: network ${_iso_net} will be created"
		fi
	else
		isolate_say "External mode: the worker reaches Redis through the published host"
		isolate_say "port; no dedicated network (skipped)."
	fi
	isolate_step "3. Worker environment"
	isolate_say "WEB_RENDER_REDIS_URL (web-render user) and optional Chromium egress:"
	isolate_say "RENDER_PROXY_SERVER sends all traffic through a forward proxy you control;"
	isolate_say "RENDER_HOST_RESOLVER_RULES (e.g. 'MAP * ~NOTFOUND' for block renders only)."
	isolate_say "Both are Chromium settings inside the worker, not a network boundary."
	isolate_step "4. Sidecar key"
	if [ "$(deploy_env_get CONTENT_VERSION_MODE)" = "encrypted" ]; then
		isolate_say "Encrypted mode: WEB_RENDER_SIDECAR_KEY is derived in the app image."
	else
		isolate_say "Plaintext mode: no worker key needed (skipped)."
	fi
	isolate_step "5. Restart redis, app and worker (brief downtime), then verify"

	if [ "${_iso_interactive}" = "1" ]; then
		isolate_step "Questions"
		if [ "${_iso_proxy_set}" = "0" ]; then
			ask_value _iso_proxy "RENDER_PROXY_SERVER (proxy URL; Enter keeps, 'none' clears)" "${_iso_cur_proxy}"
			[ "${_iso_proxy}" = "${_iso_cur_proxy}" ] || _iso_proxy_set=1
		fi
		if [ "${_iso_rules_set}" = "0" ]; then
			ask_value _iso_rules "RENDER_HOST_RESOLVER_RULES (Enter keeps, 'none' clears)" "${_iso_cur_rules}"
			[ "${_iso_rules}" = "${_iso_cur_rules}" ] || _iso_rules_set=1
		fi
		if [ "${_iso_has_worker}" = "1" ] && [ "${_iso_rotate}" = "0" ] &&
			ask_yes_no "Rotate the web-render Redis password?" n; then
			_iso_rotate=1
		fi
	fi
	for _iso_v in "${_iso_proxy}" "${_iso_rules}"; do
		case "${_iso_v}" in
			*,*) die "RENDER_PROXY_SERVER / RENDER_HOST_RESOLVER_RULES must not contain commas" ;;
		esac
	done

	# ── plan (dry run in the app image) ──
	_iso_work="${DEPLOY_DIR}/.ldcmd-isolate"
	rm -rf "${_iso_work}"
	(umask 077 && mkdir -p "${_iso_work}") || die "cannot create ${_iso_work}"
	: > "${_iso_work}/current.acl"
	if [ -n "${_iso_aclfile}" ]; then
		isolate_compose exec -T redis cat "${_iso_aclfile}" \
			> "${_iso_work}/current.acl" 2>/dev/null || : > "${_iso_work}/current.acl"
	fi
	set -- --mode "${_iso_mode}" --current-acl /deploy/.ldcmd-isolate/current.acl \
		--acl-out /deploy/.ldcmd-isolate/users.acl --redis-version "${_iso_ver}"
	[ "${_iso_mode}" = "internal" ] && set -- "$@" --network-name "${_iso_net}"
	[ -n "${_iso_aclfile}" ] && set -- "$@" --active-aclfile "${_iso_aclfile}"
	[ "${_iso_rotate}" = "1" ] && set -- "$@" --rotate-worker-password
	[ "${_iso_proxy_set}" = "1" ] && set -- "$@" --proxy-server "${_iso_proxy}"
	[ "${_iso_rules_set}" = "1" ] && set -- "$@" --resolver-rules "${_iso_rules}"
	_iso_plan="$(run_app_image_script web_render_isolate.ts "$@" --dry-run)" || {
		rm -rf "${_iso_work}"
		die "planning failed (needs a LIMEDOC_IMAGE that ships scripts/web_render_isolate.ts)"
	}
	_iso_changed="$(printf '%s\n' "${_iso_plan}" | sed -n 's/^LDCMD_ISOLATE_CHANGED=//p')"
	_iso_acl_changed="$(printf '%s\n' "${_iso_plan}" | sed -n 's/^LDCMD_ISOLATE_ACL_CHANGED=//p')"
	_iso_overlay_new="$(printf '%s\n' "${_iso_plan}" | sed -n 's/^LDCMD_ISOLATE_OVERLAY_WRITTEN=//p')"

	isolate_step "Plan"
	isolate_say ".env keys to change: ${_iso_changed:-none}"
	[ "${_iso_acl_changed}" = "1" ] && isolate_say "Redis ACL file: update"
	[ "${_iso_overlay_new}" = "1" ] && isolate_say "compose overlay: write ${ISOLATION_OVERLAY_FILE}"
	if [ "${_iso_mode}" = "internal" ] && [ "${_iso_net_exists}" = "0" ]; then
		if [ "${_iso_internal}" = "1" ]; then
			isolate_say "docker network create --internal ${_iso_net}"
		else
			isolate_say "docker network create ${_iso_net}"
		fi
	fi
	if [ -z "${_iso_changed}" ] && [ "${_iso_acl_changed}" != "1" ] &&
		[ "${_iso_overlay_new}" != "1" ] && [ -n "${_iso_aclfile}" ] &&
		{ [ "${_iso_mode}" = "external" ] || [ "${_iso_net_exists}" = "1" ]; }; then
		rm -rf "${_iso_work}"
		info "already isolated; nothing to change"
		sidecar_write_keys web-render || true
		isolate_verify && { info "isolation checks passed"; return 0; }
		die "isolation checks failed (see above)"
	fi
	if [ "${_iso_interactive}" = "1" ] &&
		! ask_yes_no "Apply these changes to ${DEPLOY_DIR}?" n; then
		rm -rf "${_iso_work}"
		info "nothing changed"
		return 0
	fi

	# ── apply ──
	_iso_res="$(run_app_image_script web_render_isolate.ts "$@")" || {
		rm -rf "${_iso_work}"
		die "writing the deploy config failed (nothing applied)"
	}
	_iso_aclpath="$(printf '%s\n' "${_iso_res}" | sed -n 's/^LDCMD_ISOLATE_ACLFILE=//p')"
	_iso_backup="$(printf '%s\n' "${_iso_res}" | sed -n 's/^LDCMD_ISOLATE_ENV_BACKUP=//p')"
	case "${_iso_backup}" in
		/deploy/*) _iso_backup="${DEPLOY_DIR}/${_iso_backup#/deploy/}" ;;
	esac
	printf '%s\n' "${_iso_res}" | sed -n 's/^note: /ldcmd: note: /p' >&2
	[ -n "${_iso_backup}" ] && info "previous .env saved as ${_iso_backup}"
	sidecar_write_keys web-render ||
		die "could not write WEB_RENDER_SIDECAR_KEY (encrypted mode); fix and re-run"

	if [ "${_iso_mode}" = "internal" ] && [ "${_iso_net_exists}" = "0" ]; then
		if [ "${_iso_internal}" = "1" ]; then
			docker network create --internal --label com.limedoc.purpose=web-render \
				"${_iso_net}" >/dev/null || die "docker network create --internal ${_iso_net} failed"
			info "created internal network ${_iso_net} (no route out)"
		else
			docker network create --label com.limedoc.purpose=web-render \
				"${_iso_net}" >/dev/null || die "docker network create ${_iso_net} failed"
			info "created network ${_iso_net}"
		fi
	fi

	# Validate the worker rules on the live server before Redis has to load
	# them from the file (a bad line would stop Redis from starting).
	_iso_rules_line="$(sed -n 's/^user web-render on #[0-9a-f]* //p' "${_iso_work}/users.acl")"
	[ -n "${_iso_rules_line}" ] || die "generated ACL file has no web-render user"
	_iso_probe="$(printf 'ACL SETUSER ldcmd-probe off %s\nACL DELUSER ldcmd-probe\n' "${_iso_rules_line}" |
		redis_cli_as "${_iso_old_user}" "${_iso_old_pw}")"
	case "${_iso_probe}" in
		*ERR*|*rror*|*NOAUTH*|*WRONGPASS*|*NOPERM*)
			die "Redis rejected the web-render ACL rules: ${_iso_probe} (restore ${_iso_backup:-.env} and report this)" ;;
	esac

	_iso_aclpath="${_iso_aclpath:-/data/users.acl}"
	# shellcheck disable=SC2016
	isolate_compose exec -T redis sh -c 'umask 077; cat > "$1.ldcmd-new" &&
		chown --reference="$(dirname "$1")" "$1.ldcmd-new" 2>/dev/null;
		mv -f "$1.ldcmd-new" "$1"' sh "${_iso_aclpath}" \
		< "${_iso_work}/users.acl" || die "cannot write ${_iso_aclpath} in the redis container"
	info "installed Redis ACL file ${_iso_aclpath}"
	if [ -n "${_iso_aclfile}" ]; then
		_iso_load="$(printf 'ACL LOAD\n' | redis_cli_as "${_iso_old_user}" "${_iso_old_pw}")"
		case "${_iso_load}" in
			*ERR*)
				# shellcheck disable=SC2016
				isolate_compose exec -T redis sh -c 'cat > "$1"' sh "${_iso_aclpath}" \
					< "${_iso_work}/current.acl" || true
				die "ACL LOAD failed (${_iso_load}); previous ACL file restored" ;;
		esac
		info "Redis reloaded its users (ACL LOAD)"
	fi
	rm -rf "${_iso_work}"

	if [ "${_iso_restart}" = "1" ] && [ "${_iso_interactive}" = "1" ] &&
		! ask_yes_no "Restart redis, app and the worker now (brief downtime)?" y; then
		_iso_restart=0
	fi
	if [ "${_iso_restart}" = "0" ]; then
		info "config written; not restarted. Apply with: ldcmd up  (then: ldcmd sidecar isolate web-render --verify)"
		[ -z "${_iso_aclfile}" ] &&
			info "until redis restarts the app keeps working; the new REDIS_URL takes effect with the restart"
		return 0
	fi

	# ── restart: redis (new users / network) → app (new REDIS_URL) → worker ──
	prod_core_compose_args
	step "restarting redis"
	run_long "redis restart" isolate_compose up -d --wait redis ||
		die "redis did not come back healthy; undo: remove REDIS_ARGS from .env (or restore ${_iso_backup:-the .env backup}) and run ldcmd up"
	step "recreating app"
	run_long "app recreate" isolate_compose up -d --wait --no-deps --force-recreate app ||
		die "app did not become healthy with the new REDIS_URL (docker compose logs app)"
	# A new REDIS_URL password also concerns every other sidecar that reads
	# REDIS_URL from the deploy .env (vectorsearch-lite): recreate them all.
	case ",${_iso_changed}," in
		*,REDIS_URL,*)
			info "recreating sidecars (REDIS_URL changed)"
			(cmd_sidecar_up) ||
				info "WARNING: sidecar restart failed; run: ldcmd sidecar up"
			;;
		*)
			info "recreating web-render worker"
			(cmd_sidecar_up web-render) ||
				info "WARNING: worker restart failed; run: ldcmd sidecar up web-render"
			;;
	esac

	_iso_vrc=0
	isolate_verify || _iso_vrc=$?

	isolate_step "Summary"
	isolate_say "Redis users: ${_iso_old_user:-default} (app, REDIS_URL) and web-render (WEB_RENDER_REDIS_URL), stored in ${_iso_aclpath}"
	if [ "${_iso_mode}" = "internal" ]; then
		isolate_say "Network: worker on ${_iso_net}; redis + app joined via ${ISOLATION_OVERLAY_FILE}"
		if network_is_internal "${_iso_net}"; then
			isolate_say "         internal: no route to outside addresses"
		else
			isolate_say "         plain bridge: separated from the other containers; outbound"
			isolate_say "         connections are not restricted by the network"
		fi
	fi
	[ -n "${_iso_backup}" ] && isolate_say "Previous .env: ${_iso_backup}"
	isolate_say "Re-check any time: ldcmd sidecar isolate web-render --verify"
	isolate_step "Undo"
	isolate_say "1. rm ${DEPLOY_DIR}/${ISOLATION_OVERLAY_FILE}; delete WEB_RENDER_NETWORK_NAME"
	isolate_say "   from .env (Redis auth and the worker's Redis user stay: ldcmd redis secure)"
	isolate_say "2. ldcmd up; docker network rm ${_iso_net}"
	[ "${_iso_vrc}" = "0" ] || die "${_iso_vrc} check(s) failed (see Verify above)"
	info "web-render isolation complete"
}

# ── redis secure ──────────────────────────────────────────────────────────────
#
# Redis auth for every deploy (docs/install "Redis auth"): ACL file in the
# Redis volume (--aclfile via REDIS_ARGS), a password for the app user
# (REDIS_URL) and one restricted user per sidecar (WEB_RENDER_REDIS_URL,
# VECTORSEARCH_REDIS_URL). The deploy-side files come from
# /app/scripts/redis_secure.ts in the app image; passwords reach redis-cli on
# stdin only. Run by bootstrap and update; safe to re-run.

# Sidecar users as <user>:<env key> (lib/ops/redis_auth.ts SIDECAR_REDIS_USERS).
REDIS_SIDECAR_USERS="web-render:WEB_RENDER_REDIS_URL vectorsearch:VECTORSEARCH_REDIS_URL"

redis_secure_usage() {
	help_text redis secure >&2
}

# redis_secure_missing — comma list of deploy .env keys `redis secure` still
# has to write (empty = done): a password in REDIS_URL, every sidecar URL.
redis_secure_missing() {
	_rsm=""
	[ -n "$(redis_url_password "$(deploy_env_get REDIS_URL)")" ] || _rsm="REDIS_URL"
	for _rsm_pair in ${REDIS_SIDECAR_USERS}; do
		[ -n "$(deploy_env_get "${_rsm_pair#*:}")" ] ||
			_rsm="${_rsm:+${_rsm},}${_rsm_pair#*:}"
	done
	printf '%s\n' "${_rsm}"
}

# redis_secure_verify — checks after apply (or `--verify`). Returns failures.
redis_secure_verify() {
	_iso_fails=0
	_rv_url="$(deploy_env_get REDIS_URL)"
	_rv_user="$(redis_url_user "${_rv_url}")"
	_rv_pw="$(redis_url_password "${_rv_url}")"
	isolate_step "Verify"
	_rv_out="$(printf 'PING\n' | redis_cli_as "" "")"
	case "${_rv_out}" in
		*NOAUTH*) isolate_check 0 "Redis refuses clients without a password" ;;
		*) isolate_check 1 "Redis refuses clients without a password (got: ${_rv_out})" ;;
	esac
	_rv_out="$(printf 'PING\n' | redis_cli_as "${_rv_user}" "${_rv_pw}")"
	case "${_rv_out}" in
		*PONG*) isolate_check 0 "app credentials (REDIS_URL) are accepted" ;;
		*) isolate_check 1 "app credentials (REDIS_URL) are accepted" ;;
	esac
	for _rv_pair in ${REDIS_SIDECAR_USERS}; do
		_rv_su="${_rv_pair%%:*}"
		_rv_key="${_rv_pair#*:}"
		_rv_surl="$(deploy_env_get "${_rv_key}")"
		if [ -z "${_rv_surl}" ]; then
			isolate_check 1 "${_rv_key} is set in .env"
			continue
		fi
		_rv_out="$(printf 'PING\nGET sessions:x\n' |
			redis_cli_as "${_rv_su}" "$(redis_url_password "${_rv_surl}")")"
		case "${_rv_out}" in
			*PONG*NOPERM*) isolate_check 0 "${_rv_su} user works and cannot read app keys" ;;
			*) isolate_check 1 "${_rv_su} user works and cannot read app keys" ;;
		esac
	done
	_rv_aclf="$(printf 'CONFIG GET aclfile\n' | redis_cli_as "${_rv_user}" "${_rv_pw}" |
		sed -n '/^aclfile$/{n;p;}' | head -1)"
	if [ -n "${_rv_aclf}" ]; then
		isolate_check 0 "Redis loads users from ${_rv_aclf} (survives restarts)"
	else
		isolate_check 1 "Redis runs with --aclfile (users would be lost on restart)"
	fi
	return "${_iso_fails}"
}

# redis_secure_repair_aclfile — Redis that cannot start because REDIS_ARGS
# names an ACL file missing from its volume (a redis secure before 0.5.2
# wrote .env and then failed): write the file from the passwords in .env
# and start redis + app. Returns 0 when there is nothing to repair; the
# normal redis secure flow follows either way.
redis_secure_repair_aclfile() {
	_rr_args="$(deploy_env_get REDIS_ARGS | tr -d "\"'")"
	case "${_rr_args}" in *--aclfile*) ;; *) return 0 ;; esac
	_rr_url="$(deploy_env_get REDIS_URL)"
	_rr_ping="$(printf 'PING\n' |
		redis_cli_as "$(redis_url_user "${_rr_url}")" "$(redis_url_password "${_rr_url}")" \
		2>/dev/null || true)"
	case "${_rr_ping}" in *PONG*) return 0 ;; esac
	_rr_path="$(printf '%s\n' "${_rr_args}" | sed -n 's/.*--aclfile[ =]\([^ ]*\).*/\1/p')"
	# Only a file in the Redis volume; anything else is the operator's.
	case "${_rr_path}" in /data/*) ;; *) return 0 ;; esac
	# shellcheck disable=SC2016
	if isolate_compose run --rm --no-deps -T --entrypoint sh redis \
		-c 'test -f "$1"' sh "${_rr_path}" >/dev/null 2>&1; then
		return 0
	fi
	_rr_ver="$(isolate_compose run --rm --no-deps -T --entrypoint redis-server redis \
		--version 2>/dev/null | sed -n 's/.* v=\([0-9][0-9.]*\).*/\1/p' | head -1)"
	case "${_rr_ver}" in
		[0-6].*|"")
			die "Redis cannot start: ${_rr_path} is missing, and the Redis image is not Redis 7+ (${_rr_ver:-version unknown})" ;;
	esac

	isolate_step "Repair"
	isolate_say "Redis cannot start: REDIS_ARGS names ${_rr_path}, which is missing in"
	isolate_say "the Redis volume (an earlier redis secure did not finish). ldcmd writes"
	isolate_say "it from the passwords in .env, then starts redis and the app."
	if [ "${_rs_interactive}" = "1" ] && ! ask_yes_no "Repair now?" y; then
		die "nothing changed; Redis stays down"
	fi
	_rr_work="${DEPLOY_DIR}/.ldcmd-redis"
	rm -rf "${_rr_work}"
	(umask 077 && mkdir -p "${_rr_work}") || die "cannot create ${_rr_work}"
	: > "${_rr_work}/current.acl"
	if [ "$(id -u)" = "0" ]; then
		chown -R 10001:10001 "${_rr_work}" ||
			die "cannot hand ${_rr_work} to the container user (UID 10001)"
	fi
	_rr_res="$(run_app_image_script redis_secure.ts \
		--current-acl /deploy/.ldcmd-redis/current.acl \
		--acl-out /deploy/.ldcmd-redis/users.acl \
		--redis-version "${_rr_ver}" --active-aclfile "${_rr_path}")" || {
		rm -rf "${_rr_work}"
		die "repair: generating the ACL file failed (nothing applied)"
	}
	_rr_backup="$(printf '%s\n' "${_rr_res}" | sed -n 's/^LDCMD_REDIS_ENV_BACKUP=//p')"
	case "${_rr_backup}" in
		/deploy/*) info "repair: .env completed; previous .env saved as ${DEPLOY_DIR}/${_rr_backup#/deploy/}" ;;
	esac
	# shellcheck disable=SC2016
	isolate_compose run --rm --no-deps -T --entrypoint sh redis \
		-c 'umask 077; cat > "$1"' sh "${_rr_path}" < "${_rr_work}/users.acl" || {
		rm -rf "${_rr_work}"
		die "repair: cannot write ${_rr_path} into the Redis volume"
	}
	rm -rf "${_rr_work}"
	info "repair: wrote ${_rr_path}"
	step "starting redis and app"
	run_long "redis start" isolate_compose up -d --wait redis ||
		die "redis still does not start (docker compose logs redis)"
	run_long "app start" isolate_compose up -d --wait app ||
		die "app did not become healthy (docker compose logs app)"
	info "repair: Redis loads its users from ${_rr_path}"
}

cmd_redis_secure() {
	_rs_yes="${LDCMD_ASSUME_YES:-0}"
	_rs_verify_only=0
	_rs_rotate=0
	_rs_restart=1
	_rs_sidecars=1
	while [ $# -gt 0 ]; do
		case "$1" in
			-y|--yes) _rs_yes=1; shift ;;
			--verify) _rs_verify_only=1; shift ;;
			--rotate-sidecar-passwords) _rs_rotate=1; shift ;;
			--no-restart) _rs_restart=0; shift ;;
			--no-sidecars) _rs_sidecars=0; shift ;;
			-h|--help) redis_secure_usage; return 0 ;;
			*) redis_secure_usage; die "redis secure: unknown option $1" ;;
		esac
	done
	_rs_interactive=0
	if [ "${_rs_yes}" != "1" ] && [ "${_rs_verify_only}" != "1" ]; then
		is_tty ||
			die "redis secure: no TTY to ask on; re-run with --yes to apply non-interactively"
		_rs_interactive=1
	fi

	resolve_prod_deploy_dir
	prod_core_compose_args
	command -v docker >/dev/null 2>&1 || die "docker is required"
	[ "${_rs_verify_only}" = "1" ] || redis_secure_repair_aclfile
	isolate_compose ps -q redis 2>/dev/null | grep -q . ||
		die "redis is not running in ${DEPLOY_DIR} (start it with: ldcmd up). Redis outside this deploy: create the users yourself (docs/install \"Redis auth\")"

	if [ "${_rs_verify_only}" = "1" ]; then
		redis_secure_verify && { info "Redis auth checks passed"; return 0; }
		die "Redis auth checks failed (re-run: ldcmd redis secure)"
	fi

	_rs_old_url="$(deploy_env_get REDIS_URL)"
	_rs_old_user="$(redis_url_user "${_rs_old_url}")"
	_rs_old_pw="$(redis_url_password "${_rs_old_url}")"
	_rs_state="$(printf 'INFO server\nCONFIG GET aclfile\n' |
		redis_cli_as "${_rs_old_user}" "${_rs_old_pw}")"
	case "${_rs_state}" in
		*NOAUTH*|*WRONGPASS*)
			die "Redis rejects the credentials in REDIS_URL (${DEPLOY_DIR}/.env); fix REDIS_URL first" ;;
	esac
	_rs_ver="$(printf '%s\n' "${_rs_state}" | sed -n 's/^redis_version:\(.*\)$/\1/p' | head -1)"
	_rs_aclfile="$(printf '%s\n' "${_rs_state}" | sed -n '/^aclfile$/{n;p;}' | head -1)"
	if [ -z "${_rs_state}" ]; then
		case "$(deploy_env_get REDIS_ARGS)" in
			*--aclfile*)
				die "Redis does not answer although the ACL file named in REDIS_ARGS exists (docker compose logs redis)" ;;
		esac
		die "Redis does not answer (docker compose logs redis); start it with ldcmd up, then re-run"
	fi
	case "${_rs_ver}" in
		[0-6].*|"") die "Redis ${_rs_ver:-?} is too old: key-scoped ACL users need Redis 7+ (set REDIS_IMAGE)" ;;
	esac
	if [ -z "${_rs_aclfile}" ] &&
		! isolate_compose exec -T redis sh -c \
			'grep -qs REDIS_ARGS /entrypoint.sh /usr/local/bin/docker-entrypoint.sh' \
			>/dev/null 2>&1; then
		die "REDIS_IMAGE does not honour REDIS_ARGS (redis-stack does). Start redis with '--aclfile /data/users.acl' (compose command override, file must exist), then re-run"
	fi

	# ── plan (dry run in the app image) ──
	_rs_work="${DEPLOY_DIR}/.ldcmd-redis"
	rm -rf "${_rs_work}"
	(umask 077 && mkdir -p "${_rs_work}") || die "cannot create ${_rs_work}"
	: > "${_rs_work}/current.acl"
	if [ -n "${_rs_aclfile}" ]; then
		isolate_compose exec -T redis cat "${_rs_aclfile}" \
			> "${_rs_work}/current.acl" 2>/dev/null || : > "${_rs_work}/current.acl"
	fi
	# redis_secure.ts runs in the app image as the container user: it must
	# read current.acl and write users.acl here (root's umask 077 dir is
	# closed to it).
	if [ "$(id -u)" = "0" ]; then
		chown -R 10001:10001 "${_rs_work}" ||
			die "cannot hand ${_rs_work} to the container user (UID 10001)"
	fi
	set -- --current-acl /deploy/.ldcmd-redis/current.acl \
		--acl-out /deploy/.ldcmd-redis/users.acl --redis-version "${_rs_ver}"
	[ -n "${_rs_aclfile}" ] && set -- "$@" --active-aclfile "${_rs_aclfile}"
	[ "${_rs_rotate}" = "1" ] && set -- "$@" --rotate-sidecar-passwords
	_rs_plan="$(run_app_image_script redis_secure.ts "$@" --dry-run)" || {
		rm -rf "${_rs_work}"
		die "planning failed (needs a LIMEDOC_IMAGE that ships scripts/redis_secure.ts, 0.4.5+)"
	}
	_rs_changed="$(printf '%s\n' "${_rs_plan}" | sed -n 's/^LDCMD_REDIS_CHANGED=//p')"
	_rs_acl_changed="$(printf '%s\n' "${_rs_plan}" | sed -n 's/^LDCMD_REDIS_ACL_CHANGED=//p')"

	printf 'Redis auth for %s (Redis %s)\n' "${DEPLOY_DIR}" "${_rs_ver}" >&2
	if [ -z "${_rs_changed}" ] && [ "${_rs_acl_changed}" != "1" ] &&
		[ -n "${_rs_aclfile}" ]; then
		rm -rf "${_rs_work}"
		info "Redis auth already set up; nothing to change"
		redis_secure_verify && { info "Redis auth checks passed"; return 0; }
		die "Redis auth checks failed (see above)"
	fi
	isolate_step "Plan"
	isolate_say "Sessions live in Redis: only clients with a password may reach it."
	isolate_say ".env keys to change: ${_rs_changed:-none}"
	[ "${_rs_acl_changed}" = "1" ] && isolate_say "Redis ACL file: update (hashed passwords only)"
	[ -z "${_rs_aclfile}" ] &&
		isolate_say "REDIS_ARGS gets '--aclfile /data/users.acl' (Redis restart)"
	case ",${_rs_changed}," in
		*,REDIS_URL,*)
			isolate_say "REDIS_URL gets a password: external Redis clients (monitoring,"
			isolate_say "scripts) need the new REDIS_URL afterwards." ;;
	esac
	isolate_say "Sidecars get their own users: web-render (render keys), vectorsearch"
	isolate_say "(search keys); restart: redis → app → sidecars."
	if [ "${_rs_interactive}" = "1" ] &&
		! ask_yes_no "Apply these changes to ${DEPLOY_DIR}?" n; then
		rm -rf "${_rs_work}"
		info "nothing changed"
		return 0
	fi

	# ── apply ──
	_rs_res="$(run_app_image_script redis_secure.ts "$@")" || {
		rm -rf "${_rs_work}"
		die "writing the deploy config failed (nothing applied)"
	}
	_rs_aclpath="$(printf '%s\n' "${_rs_res}" | sed -n 's/^LDCMD_REDIS_ACLFILE=//p')"
	_rs_backup="$(printf '%s\n' "${_rs_res}" | sed -n 's/^LDCMD_REDIS_ENV_BACKUP=//p')"
	case "${_rs_backup}" in
		/deploy/*) _rs_backup="${DEPLOY_DIR}/${_rs_backup#/deploy/}" ;;
	esac
	printf '%s\n' "${_rs_res}" | sed -n 's/^note: /ldcmd: note: /p' >&2
	[ -n "${_rs_backup}" ] && info "previous .env saved as ${_rs_backup}"

	# Validate each sidecar's rules on the live server before Redis has to
	# load them from the file (a bad line would stop Redis from starting).
	_rs_probe_in=""
	for _rs_pair in ${REDIS_SIDECAR_USERS}; do
		_rs_su="${_rs_pair%%:*}"
		_rs_line="$(sed -n "s/^user ${_rs_su} on #[0-9a-f]* //p" "${_rs_work}/users.acl")"
		[ -n "${_rs_line}" ] || {
			rm -rf "${_rs_work}"
			die "generated ACL file has no ${_rs_su} user (restore ${_rs_backup:-.env})"
		}
		_rs_probe_in="${_rs_probe_in}ACL SETUSER ldcmd-probe off ${_rs_line}
ACL DELUSER ldcmd-probe
"
	done
	_rs_probe="$(printf '%s' "${_rs_probe_in}" | redis_cli_as "${_rs_old_user}" "${_rs_old_pw}")"
	case "${_rs_probe}" in
		*ERR*|*rror*|*NOAUTH*|*WRONGPASS*|*NOPERM*)
			rm -rf "${_rs_work}"
			die "Redis rejected the sidecar ACL rules: ${_rs_probe} (restore ${_rs_backup:-.env} and report this)" ;;
	esac

	_rs_aclpath="${_rs_aclpath:-/data/users.acl}"
	# shellcheck disable=SC2016
	isolate_compose exec -T redis sh -c 'umask 077; cat > "$1.ldcmd-new" &&
		chown --reference="$(dirname "$1")" "$1.ldcmd-new" 2>/dev/null;
		mv -f "$1.ldcmd-new" "$1"' sh "${_rs_aclpath}" \
		< "${_rs_work}/users.acl" || {
		rm -rf "${_rs_work}"
		die "cannot write ${_rs_aclpath} in the redis container (restore ${_rs_backup:-.env})"
	}
	info "installed Redis ACL file ${_rs_aclpath}"
	if [ -n "${_rs_aclfile}" ]; then
		_rs_load="$(printf 'ACL LOAD\n' | redis_cli_as "${_rs_old_user}" "${_rs_old_pw}")"
		case "${_rs_load}" in
			*ERR*)
				# shellcheck disable=SC2016
				isolate_compose exec -T redis sh -c 'cat > "$1"' sh "${_rs_aclpath}" \
					< "${_rs_work}/current.acl" || true
				rm -rf "${_rs_work}"
				die "ACL LOAD failed (${_rs_load}); previous ACL file restored" ;;
		esac
		info "Redis reloaded its users (ACL LOAD)"
	fi
	rm -rf "${_rs_work}"

	if [ "${_rs_restart}" = "1" ] && [ "${_rs_interactive}" = "1" ] &&
		! ask_yes_no "Restart redis, app and sidecars now (brief downtime)?" y; then
		_rs_restart=0
	fi
	if [ "${_rs_restart}" = "0" ]; then
		info "config written; not restarted. Apply with: ldcmd up  (then: ldcmd redis secure --verify)"
		return 0
	fi

	# Redis restarts only to pick up REDIS_ARGS; the app only for a new REDIS_URL.
	case ",${_rs_changed}," in
		*,REDIS_ARGS,*)
			step "restarting redis"
			run_long "redis restart" isolate_compose up -d --wait redis ||
				die "redis did not come back healthy; undo: restore ${_rs_backup:-the .env backup} and run ldcmd up" ;;
	esac
	case ",${_rs_changed}," in
		*,REDIS_URL,*|*,REDIS_ARGS,*)
			step "recreating app"
			run_long "app recreate" isolate_compose up -d --wait --no-deps --force-recreate app ||
				die "app did not become healthy with the new REDIS_URL (docker compose logs app)" ;;
	esac
	if [ "${_rs_sidecars}" = "1" ] && [ -n "${_rs_changed}" ]; then
		info "recreating sidecars (Redis credentials changed)"
		(cmd_sidecar_up) || info "WARNING: sidecar restart failed; run: ldcmd sidecar up"
	fi

	_rs_vrc=0
	redis_secure_verify || _rs_vrc=$?
	isolate_step "Summary"
	isolate_say "Redis users: ${_rs_old_user:-default} (app, REDIS_URL), web-render (WEB_RENDER_REDIS_URL),"
	isolate_say "vectorsearch (VECTORSEARCH_REDIS_URL), stored in ${_rs_aclpath}"
	[ -n "${_rs_backup}" ] && isolate_say "Previous .env: ${_rs_backup}"
	isolate_say "Re-check any time: ldcmd redis secure --verify"
	[ "${_rs_vrc}" = "0" ] || die "${_rs_vrc} check(s) failed (see Verify above)"
	info "Redis auth complete"
}

# Redis auth for bootstrap and update (ldcmd redis secure --yes). Sessions
# live in Redis: when the setup fails, the core stack is stopped and ldcmd
# ends, unless $1 = 1 (--allow-insecure-redis, LDCMD_ALLOW_INSECURE_REDIS=1).
# Returns 1 when it failed and the instance was left running.
redis_secure_or_stop() {
	if (cmd_redis_secure --yes --no-sidecars); then
		return 0
	fi
	if [ "$1" = "1" ]; then
		info "WARNING: Redis auth setup failed; --allow-insecure-redis keeps the instance running. Sessions and caches in Redis may be reachable without a password. Fix the cause above, then run: ldcmd redis secure"
		return 1
	fi
	info "Redis auth setup failed: stopping the instance (redis + app) — it must not serve with a Redis whose auth is not verified"
	(
		resolve_prod_deploy_dir
		prod_core_compose_args
		# shellcheck disable=SC2086
		docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} stop
	) || info "warn: could not stop the core stack; stop it yourself: ldcmd down"
	die "Redis auth is not set up and the instance was stopped. Fix the cause above, start it (ldcmd up) and run ldcmd redis secure right away. To keep an instance running without verified Redis auth, pass --allow-insecure-redis (Redis outside this deploy: create the users yourself, docs/install \"Redis auth\", and pass the flag)"
}

cmd_prod_up() {
	resolve_prod_deploy_dir
	ensure_host_data_mounts
	prod_core_up
	# Subshell: a die in sidecar up must not turn a started core into a failure.
	(cmd_sidecar_up "$@") || info "some sidecars did not start (see above)"
}

cmd_prod_down() {
	cmd_sidecar_down "$@" || true
	prod_core_down
}

cmd_prod_status() {
	resolve_prod_deploy_dir
	prod_core_compose_args
	info "core services:"
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} ps || true
	cmd_sidecar_status
}

# Read KEY=value from deploy env file (first match).
deploy_env_get() {
	_key="$1"
	_envf="$(deploy_env_file)"
	[ -f "${_envf}" ] || return 0
	grep -E "^${_key}=" "${_envf}" 2>/dev/null | head -1 | cut -d= -f2- |
		tr -d '\r' | tr -d '"' | tr -d "'"
}

# True if mount source is a host bind path (Compose path rule).
data_is_host_mount() {
	case "$1" in
		. | .. | ./* | ../* | /* | */*) return 0 ;;
		*) return 1 ;;
	esac
}

# Resolve LIMEDOC_DATA_MOUNT to an absolute host path.
data_resolve_abs_mount() {
	_m="$1"
	case "${_m}" in
		/*) printf '%s\n' "${_m}" ;;
		./*) printf '%s\n' "${DEPLOY_DIR}/${_m#./}" ;;
		*) printf '%s\n' "${DEPLOY_DIR}/${_m}" ;;
	esac
}

data_is_limedoc_data_dir() {
	_p="$1"
	[ -d "${_p}" ] || return 1
	[ -d "${_p}/tree" ] || return 1
	[ -d "${_p}/documents" ] || return 1
	[ -d "${_p}/config" ] || return 1
	[ -d "${_p}/blobs" ] || return 1
	[ -d "${_p}/blocks" ] || return 1
	[ -d "${_p}/cache" ] || return 1
	return 0
}

data_is_new_scaffold() {
	_p="$1"
	[ -d "${_p}" ] || return 1
	_count="$(find "${_p}" -mindepth 1 -maxdepth 1 ! -name '.' ! -name '..' 2>/dev/null | wc -l | tr -d ' ')"
	[ "${_count}" = "0" ] && return 0
	if [ "${_count}" = "1" ] && [ -d "${_p}/cache" ]; then
		return 0
	fi
	return 1
}

# Validate/create host data dir (leaf mkdir only). Mirrors lib/ops/data_mount.ts.
# fix_data_ownership <dir> [errfile]: chown to 10001:10001 what is not owned
# that way; errors go to errfile (default: stderr).
fix_data_ownership() {
	find "$1" \( ! -user 10001 -o ! -group 10001 \) \
		-exec chown -h 10001:10001 {} + 2>"${2:-/dev/stderr}"
}

ensure_host_data_dir() {
	_abs="$1"
	_abs="${_abs%/}"
	[ -n "${_abs}" ] || die "empty host data path"
	[ "${_abs}" != "/" ] || die "refusing to use filesystem root as data dir"

	_parent="$(dirname "${_abs}")"
	if data_is_limedoc_data_dir "${_parent}"; then
		die "refusing nested data dir under existing Limedoc data at ${_parent}"
	fi

	if [ -e "${_abs}" ]; then
		[ -d "${_abs}" ] || die "${_abs} exists but is not a directory"
		if ! data_is_new_scaffold "${_abs}" && ! data_is_limedoc_data_dir "${_abs}"; then
			die "${_abs} is not empty and is not a Limedoc data dir (need tree/documents/config/blobs/blocks/cache/)"
		fi
	else
		[ -d "${_parent}" ] ||
			die "parent directory does not exist: ${_parent} (will not create deep paths; create the parent first)"
		(umask 077 && mkdir "${_abs}") ||
			die "cannot create data directory ${_abs}"
	fi

	mkdir -p "${_abs}/cache/vectorsearch" ||
		die "cannot create ${_abs}/cache/vectorsearch"

	if [ "$(id -u)" = "0" ]; then
		# Only what is not owned by the container user yet: a chown -R of a
		# large wiki takes long on every up.
		_ho_err="${DEPLOY_DIR:-/tmp}/.ldcmd-chown.err"
		if ! run_long "data ownership (container UID 10001)" \
			fix_data_ownership "${_abs}" "${_ho_err}"; then
			info "warn: could not chown everything in ${_abs} to 10001:10001 ($(grep -c . "${_ho_err}" || true) error(s)); first:"
			info "  $(grep . "${_ho_err}" | head -1)"
			info "  the app may fail to write those paths; check the filesystem (read-only, NFS root_squash, chattr +i)"
		fi
		rm -f "${_ho_err}"
	else
		info "ensure ${_abs} is writable by container UID 10001 (chown if needed)"
	fi
}

ensure_host_data_mounts() {
	_mount="$(deploy_env_get LIMEDOC_DATA_MOUNT)"
	_mount="${_mount:-limedoc_data}"
	if ! data_is_host_mount "${_mount}"; then
		return 0
	fi
	_abs="$(data_resolve_abs_mount "${_mount}")"
	info "ensuring host data directory ${_abs}"
	ensure_host_data_dir "${_abs}"
}

# Absolute host path for LIMEDOC_DATA_MOUNT (named volume → empty).
host_data_abs_path() {
	_mount="$(deploy_env_get LIMEDOC_DATA_MOUNT)"
	_mount="${_mount:-limedoc_data}"
	if ! data_is_host_mount "${_mount}"; then
		printf '%s\n' ""
		return 0
	fi
	data_resolve_abs_mount "${_mount}"
}

# Count packs[] in data/config/installed-packs.json (0 if missing).
registry_pack_count() {
	_abs="$(host_data_abs_path)"
	_reg=""
	if [ -n "${_abs}" ] && [ -f "${_abs}/config/installed-packs.json" ]; then
		_reg="${_abs}/config/installed-packs.json"
	elif [ -f "${DEPLOY_DIR}/data/config/installed-packs.json" ]; then
		# Named-volume / under-deploy relative data after bind not visible — try common path
		_reg=""
	fi
	# Also try reading via a throwaway container when mount is a named volume.
	if [ -z "${_reg}" ]; then
		command -v python3 >/dev/null 2>&1 || {
			printf '0\n'
			return 0
		}
		# shellcheck disable=SC2086
		_out="$(docker compose ${COMPOSE_ARGS:-} ${PROFILE_ARGS:-} run --rm --no-deps -T app \
			sh -c 'test -f /app/data/config/installed-packs.json && cat /app/data/config/installed-packs.json' \
			2>/dev/null || true)"
		if [ -n "${_out}" ]; then
			printf '%s' "${_out}" | python3 -c '
import json, sys
try:
	d = json.load(sys.stdin)
	print(len(d.get("packs") or []))
except Exception:
	print(0)
'
			return 0
		fi
		printf '0\n'
		return 0
	fi
	command -v python3 >/dev/null 2>&1 || {
		printf '0\n'
		return 0
	}
	python3 -c '
import json, sys
try:
	with open(sys.argv[1], encoding="utf-8") as f:
		d = json.load(f)
	print(len(d.get("packs") or []))
except Exception:
	print(0)
' "${_reg}"
}

run_packs_restore_in_app() {
	_force_flag=""
	case "${1:-}" in
		--force) _force_flag="--force" ;;
	esac
	info "restoring packs from install registry (compose run --no-deps)"
	_env_mount=
	if [ -f "${DEPLOY_DIR}/.env" ]; then
		_env_mount="-v ${DEPLOY_DIR}/.env:/app/.env:ro"
	fi
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} run --rm --no-deps \
		${_env_mount} \
		app deno task packs:restore -- ${_force_flag}
}

# True when pack volumes already have trees (partial/full restore on disk).
pack_volumes_look_populated() {
	_env_mount=
	if [ -f "${DEPLOY_DIR}/.env" ]; then
		_env_mount="-v ${DEPLOY_DIR}/.env:/app/.env:ro"
	fi
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} run --rm --no-deps -T \
		${_env_mount} \
		app sh -c '
			test -d /app/skins/lime && exit 0
			for d in /app/plugins/*.plugin; do
				[ -d "$d" ] && exit 0
			done
			exit 1
		' >/dev/null 2>&1
}

# Archive data/config before wipe → {DEPLOY_DIR}/backups/pack-wipe-{ts}.tar.gz
archive_data_config_for_wipe() {
	_ts="$(date -u +%Y%m%dT%H%M%SZ 2>/dev/null || date +%Y%m%d%H%M%S)"
	_bak_dir="${DEPLOY_DIR}/backups"
	mkdir -p "${_bak_dir}"
	_archive="${_bak_dir}/pack-wipe-${_ts}.tar.gz"
	_abs="$(host_data_abs_path)"
	_cfg=""
	if [ -n "${_abs}" ] && [ -d "${_abs}/config" ]; then
		_cfg="${_abs}/config"
		info "archiving ${_cfg} → ${_archive}"
		tar -czf "${_archive}" -C "${_abs}" config ||
			die "failed to archive ${_cfg}"
	else
		info "archiving /app/data/config via compose run → ${_archive}"
		# shellcheck disable=SC2086
		docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} run --rm --no-deps -T app \
			sh -c 'cd /app/data && tar -czf - config' > "${_archive}" ||
			die "failed to archive data/config from container"
	fi
	info "wipe safety archive: ${_archive}"
}

wipe_install_registry_and_pack_volumes() {
	info "wiping install registry + pack volume contents"
	_abs="$(host_data_abs_path)"
	if [ -n "${_abs}" ] && [ -d "${_abs}/config" ]; then
		mkdir -p "${_abs}/config"
		printf '%s\n' '{"v":1,"packs":[]}' > "${_abs}/config/installed-packs.json"
	else
		# shellcheck disable=SC2086
		docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} run --rm --no-deps app \
			sh -c 'mkdir -p /app/data/config && printf "%s\n" "{\"v\":1,\"packs\":[]}" > /app/data/config/installed-packs.json' ||
			die "failed to clear installed-packs.json"
	fi
	# Empty pack trees inside volumes (do not docker volume rm — keeps compose project refs).
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} run --rm --no-deps app \
		sh -c 'rm -rf /app/plugins/* /app/skins/* /app/templates/* 2>/dev/null; true' ||
		info "warn: could not clear pack volume contents (volumes may be empty)"
	info "install registry wiped; pack volumes cleared"
}

cmd_packs_restore() {
	resolve_prod_deploy_dir
	export LIMEDOC_ENV_FILE="${LIMEDOC_ENV_FILE:-.env}"
	COMPOSE_ARGS="-f docker-compose.yml -f docker-compose.registry.yml --env-file .env"
	if [ -f docker-compose.wizard.publish.yml ]; then
		_mode="$(grep -E '^DEPLOY_NETWORK_MODE=' .env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true)"
		[ "${_mode}" = "external" ] &&
			COMPOSE_ARGS="${COMPOSE_ARGS} -f docker-compose.wizard.publish.yml"
	fi
	[ -f "${ISOLATION_OVERLAY_FILE}" ] &&
		COMPOSE_ARGS="${COMPOSE_ARGS} -f ${ISOLATION_OVERLAY_FILE}"
	PROFILE_ARGS="--profile redis --profile app"
	_force=""
	case "${1:-}" in
		--force) _force="--force" ;;
		"" ) ;;
		*) die "packs restore: unknown arg $1 (usage: ldcmd packs restore [--force])" ;;
	esac
	run_packs_restore_in_app ${_force} || die "packs restore failed"
	info "recreate app/sidecars so restored packs load: ldcmd up"
}

authz_usage() {
	help_text authz
}

cmd_authz() {
	_az_sub_cmd="${1:-}"
	[ "$#" -gt 0 ] && shift
	case "${_az_sub_cmd}" in
		grant-admin) _az_task="authz:grant-admin" ;;
		revoke-admin) _az_task="authz:revoke-admin" ;;
		-h|--help|help) authz_usage; return 0 ;;
		*) authz_usage; die "authz: unknown sub-command '${_az_sub_cmd}' (grant-admin|revoke-admin)" ;;
	esac
	[ "$#" -eq 1 ] && [ -n "$1" ] || { authz_usage; die "authz ${_az_sub_cmd}: expected one user id"; }
	case "$1" in
		-*) die "authz ${_az_sub_cmd}: user id must not start with '-'" ;;
	esac
	resolve_prod_deploy_dir
	prod_core_compose_args
	command -v docker >/dev/null 2>&1 || die "docker is required"
	isolate_compose ps -q app 2>/dev/null | grep -q . ||
		die "app is not running in ${DEPLOY_DIR} (start it with: ldcmd up)"
	isolate_compose exec -T app deno task -q "${_az_task}" -- "$1" ||
		die "authz ${_az_sub_cmd} failed"
}

acl_usage() {
	help_text acl
}

cmd_acl() {
	_acl_sub_cmd="${1:-}"
	[ "$#" -gt 0 ] && shift
	case "${_acl_sub_cmd}" in
		inherit-empty) ;;
		-h|--help|help) acl_usage; return 0 ;;
		*) acl_usage; die "acl: unknown sub-command '${_acl_sub_cmd}' (inherit-empty)" ;;
	esac
	_acl_apply=""
	_acl_path=""
	while [ "$#" -gt 0 ]; do
		case "$1" in
			--apply) _acl_apply="--apply" ;;
			--path)
				[ "$#" -ge 2 ] && [ -n "$2" ] || die "acl inherit-empty: --path needs a tree path"
				case "$2" in
					-*) die "acl inherit-empty: tree path must not start with '-'" ;;
				esac
				_acl_path="$2"
				shift
				;;
			*) acl_usage; die "acl inherit-empty: unknown arg $1" ;;
		esac
		shift
	done
	resolve_prod_deploy_dir
	prod_core_compose_args
	command -v docker >/dev/null 2>&1 || die "docker is required"
	isolate_compose ps -q app 2>/dev/null | grep -q . ||
		die "app is not running in ${DEPLOY_DIR} (start it with: ldcmd up)"
	if [ -n "${_acl_path}" ]; then
		# shellcheck disable=SC2086
		isolate_compose exec -T app deno task -q acl:inherit-empty -- \
			--path "${_acl_path}" ${_acl_apply} ||
			die "acl inherit-empty failed"
	else
		# shellcheck disable=SC2086
		isolate_compose exec -T app deno task -q acl:inherit-empty -- \
			${_acl_apply} || die "acl inherit-empty failed"
	fi
}

# Absolute path for a relative host mount under DEPLOY_DIR.
data_abs_host_path() {
	_m="$1"
	case "${_m}" in
		/*) printf '%s\n' "${_m}" ;;
		./*) printf '%s\n' "${DEPLOY_DIR}/${_m#./}" ;;
		*) printf '%s\n' "${DEPLOY_DIR}/${_m}" ;;
	esac
}

# Stop app + vectorsearch-lite writers before a volume copy. What was running
# is recorded in DATA_RESTART_APP / DATA_RESTART_VS (container ids;
# data_restart_writers starts those again). Dies when a writer cannot be queried or is still
# running afterwards: a copy next to a live writer is not consistent.
DATA_RESTART_APP=0
DATA_RESTART_VS=""
DATA_RESTART_HOLD=""

data_app_running_ids() {
	# shellcheck disable=SC2086
	docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} ps --status running -q app 2>/dev/null
}

# Running containers of the vectorsearch sidecar's compose project (by label:
# its compose files live in the pack tree, not here).
data_vs_running_ids() {
	docker ps -q --filter \
		"label=com.docker.compose.project=$(sidecar_compose_project_name vectorsearch-lite)" \
		2>/dev/null
}

data_stop_writers() {
	prod_core_compose_args
	_dsw_app="$(data_app_running_ids)" ||
		die "cannot query the app container (docker compose ps failed); data left untouched"
	_dsw_vsr="$(data_vs_running_ids)" ||
		die "cannot query the vectorsearch sidecar (docker ps failed); data left untouched"
	_dsw_vsr="$(printf '%s\n' "${_dsw_vsr}" | xargs)"
	if [ -z "${_dsw_app}" ] && [ -z "${_dsw_vsr}" ]; then
		info "app and vectorsearch sidecar are not running"
		return 0
	fi
	info "stopping app (and vectorsearch sidecar if present) for a consistent copy"
	if [ -n "${_dsw_app}" ]; then
		DATA_RESTART_APP=1
		# shellcheck disable=SC2086
		docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} stop app ||
			die "could not stop the app; data left untouched"
	fi
	if [ -n "${_dsw_vsr}" ]; then
		DATA_RESTART_VS="${_dsw_vsr}"
		# shellcheck disable=SC2086
		docker stop ${_dsw_vsr} >/dev/null ||
			die "could not stop the vectorsearch sidecar; data left untouched"
	fi
	_dsw_app="$(data_app_running_ids)" ||
		die "cannot query the app container after the stop; data left untouched"
	_dsw_vsr="$(data_vs_running_ids)" ||
		die "cannot query the vectorsearch sidecar after the stop; data left untouched"
	[ -z "${_dsw_app}${_dsw_vsr}" ] ||
		die "a writer is still running after the stop; data left untouched"
}

# Start what data_stop_writers stopped. With DATA_RESTART_HOLD set (a failed
# import left the volumes incomplete) nothing is started and the reason is
# printed instead.
data_restart_writers() {
	_drw_app="${DATA_RESTART_APP}"
	_drw_vs="${DATA_RESTART_VS}"
	DATA_RESTART_APP=0
	DATA_RESTART_VS=""
	[ "${_drw_app}" = "1" ] || [ -n "${_drw_vs}" ] || return 0
	if [ -n "${DATA_RESTART_HOLD}" ]; then
		info "NOT restarting the app: ${DATA_RESTART_HOLD}"
		return 0
	fi
	if [ "${_drw_app}" = "1" ]; then
		info "starting the app again"
		# shellcheck disable=SC2086
		docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} start app ||
			info "warn: could not start the app again — run: ldcmd up"
	fi
	if [ -n "${_drw_vs}" ]; then
		info "starting the vectorsearch sidecar again"
		# shellcheck disable=SC2086
		docker start ${_drw_vs} >/dev/null ||
			info "warn: could not start the vectorsearch sidecar again — run: ldcmd up"
	fi
}

# Restart on every way out of a data command (error and Ctrl-C included).
data_trap_restart() {
	trap 'data_restart_writers' EXIT
	trap 'exit 130' INT
	trap 'exit 143' TERM
}

data_trap_clear() {
	trap - EXIT INT TERM
}

# Resolve Docker volume names for data + vectorsearch (named-volume mode).
# Sets DATA_VOL_NAME and VS_VOL_NAME.
data_resolve_volume_names() {
	prod_core_compose_args
	_vs_override="$(deploy_env_get VECTORSEARCH_CACHE_VOLUME)"
	VS_VOL_NAME="${_vs_override:-limedoc_vectorsearch_cache}"

	DATA_VOL_NAME=""
	_cid=""
	# shellcheck disable=SC2086
	_cid="$(docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} ps -q app 2>/dev/null | head -1 || true)"
	if [ -n "${_cid}" ]; then
		DATA_VOL_NAME="$(docker inspect -f '{{ range .Mounts }}{{ if eq .Destination "/app/data" }}{{ .Name }}{{ end }}{{ end }}' "${_cid}" 2>/dev/null || true)"
		_vs_from_ctr="$(docker inspect -f '{{ range .Mounts }}{{ if eq .Destination "/app/data/cache/vectorsearch" }}{{ .Name }}{{ end }}{{ end }}' "${_cid}" 2>/dev/null || true)"
		if [ -n "${_vs_from_ctr}" ]; then
			VS_VOL_NAME="${_vs_from_ctr}"
		fi
	fi
	if [ -z "${DATA_VOL_NAME}" ] && command -v python3 >/dev/null 2>&1; then
		# shellcheck disable=SC2086
		DATA_VOL_NAME="$(docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} config --format json 2>/dev/null | CORE_PROJ="$(prod_compose_project_name)" python3 -c '
import json, os, sys
cfg = json.load(sys.stdin)
proj = cfg.get("name") or os.environ.get("CORE_PROJ") or "limedoc"
vols = cfg.get("volumes") or {}
v = vols.get("limedoc_data") or {}
print(v.get("name") or ("%s_limedoc_data" % proj))
' 2>/dev/null || true)"
	fi
	if [ -z "${DATA_VOL_NAME}" ]; then
		DATA_VOL_NAME="$(prod_compose_project_name)_limedoc_data"
	fi
	if command -v python3 >/dev/null 2>&1; then
		# shellcheck disable=SC2086
		_vs_cfg="$(docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} config --format json 2>/dev/null | python3 -c '
import json, sys
cfg = json.load(sys.stdin)
vols = cfg.get("volumes") or {}
v = vols.get("limedoc_vectorsearch_cache") or {}
print(v.get("name") or "")
' 2>/dev/null || true)"
		if [ -n "${_vs_cfg}" ]; then
			VS_VOL_NAME="${_vs_cfg}"
		fi
	fi
}

# Export trees hold every document and upload: only the owner may enter them.
data_cp_volume_to_dir() {
	_vol="$1"
	_dir="$2"
	(umask 077 && mkdir -p "${_dir}") || die "cannot create ${_dir}"
	step "copy volume ${_vol} → ${_dir}"
	run_long "copy" docker run --rm \
		-v "${_vol}:/from:ro" \
		-v "${_dir}:/to" \
		"${LDCMD_HELPER_IMAGE}" \
		sh -c 'cp -a /from/. /to/ && chmod go-rwx /to' ||
		die "failed copying volume ${_vol} to ${_dir}"
}

data_cp_dir_to_volume() {
	_dir="$1"
	_vol="$2"
	[ -d "${_dir}" ] || die "missing source directory ${_dir}"
	docker volume create "${_vol}" >/dev/null 2>&1 || true
	step "copy ${_dir} → volume ${_vol}"
	run_long "copy" docker run --rm \
		-v "${_vol}:/to" \
		-v "${_dir}:/from:ro" \
		"${LDCMD_HELPER_IMAGE}" \
		sh -c 'find /to -mindepth 1 -maxdepth 1 -exec rm -rf {} +; cp -a /from/. /to/' ||
		die "failed copying ${_dir} to volume ${_vol}"
}

# 0 when the volume exists and holds at least one entry.
data_volume_has_content() {
	docker volume inspect "$1" >/dev/null 2>&1 || return 1
	docker run --rm -v "$1:/from:ro" "${LDCMD_HELPER_IMAGE}" \
		sh -c '[ -n "$(ls -A /from 2>/dev/null)" ]' >/dev/null 2>&1
}

# data_snapshot_volume <volume> <snapshot volume>: copy into a new volume.
data_snapshot_volume() {
	docker volume inspect "$2" >/dev/null 2>&1 &&
		die "snapshot volume $2 exists already"
	docker volume create "$2" >/dev/null ||
		die "cannot create snapshot volume $2"
	step "snapshot volume $1 → volume $2"
	run_long "snapshot" docker run --rm \
		-v "$1:/from:ro" \
		-v "$2:/to" \
		"${LDCMD_HELPER_IMAGE}" \
		sh -c 'cp -a /from/. /to/' || {
		docker volume rm "$2" >/dev/null 2>&1 || true
		die "failed to snapshot volume $1 (nothing was changed; --no-backup skips the snapshot)"
	}
}

data_cp_host_tree() {
	_src="$1"
	_dst="$2"
	(umask 077 && mkdir -p "${_dst}") || die "cannot create ${_dst}"
	info "copy host tree ${_src} → ${_dst}"
	if [ -d "${_src}" ]; then
		cp -a "${_src}/." "${_dst}/" || die "failed copying ${_src} to ${_dst}"
		chmod go-rwx "${_dst}" 2>/dev/null ||
			info "warn: could not restrict ${_dst} to its owner (chmod go-rwx)"
	else
		die "host data path missing: ${_src}"
	fi
}

DATA_MANIFEST_NAME=".limedoc-data-manifest.json"

data_write_manifest() {
	_dir="$1"
	_mode="$2"
	_data_src="$3"
	_vs_src="$4"
	{
		echo "{"
		echo "  \"v\": 1,"
		echo "  \"ldcmd\": \"${LDCMD_VERSION}\","
		echo "  \"exportedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
		echo "  \"mode\": \"${_mode}\","
		echo "  \"dataSource\": \"${_data_src}\","
		echo "  \"vectorsearchSource\": \"${_vs_src}\","
		echo "  \"deployDir\": \"${DEPLOY_DIR}\""
		echo "}"
	} >"${_dir}/${DATA_MANIFEST_NAME}"
}

# Dies unless <dir> is a Limedoc data tree an import may restore: not empty,
# the data layout, and — when the export manifest is there — a manifest this
# ldcmd wrote.
data_validate_import_source() {
	_vis="$1"
	[ -d "${_vis}" ] || die "import directory not found: ${_vis}"
	[ -n "$(ls -A "${_vis}" 2>/dev/null)" ] ||
		die "import directory is empty: ${_vis} (an import replaces the volumes; nothing to restore)"
	data_is_limedoc_data_dir "${_vis}" ||
		die "${_vis} is not a Limedoc data tree (need tree/ documents/ config/ blobs/ blocks/ cache/)"
	_vis_m="${_vis}/${DATA_MANIFEST_NAME}"
	if [ -e "${_vis_m}" ]; then
		[ -f "${_vis_m}" ] && [ ! -L "${_vis_m}" ] ||
			die "${_vis_m} is not a regular file"
		tr -d '\r\n' < "${_vis_m}" |
			grep -Eq '"v"[[:space:]]*:[[:space:]]*1[[:space:]]*[,}]' ||
			die "${_vis_m} is not an export manifest this ldcmd reads (v 1)"
		case "$(json_str_field "${_vis_m}" mode)" in
			host|volumes) ;;
			*) die "${_vis_m} names no export mode (host or volumes)" ;;
		esac
		info "export manifest: $(json_str_field "${_vis_m}" mode) export of $(json_str_field "${_vis_m}" exportedAt) (ldcmd $(json_str_field "${_vis_m}" ldcmd))"
	else
		info "no export manifest in ${_vis} (not written by ldcmd data export); the layout check passed"
	fi
}

# Resolve export/import DIR arg under DEPLOY_DIR (absolute or relative).
data_resolve_dir_arg() {
	_arg="$1"
	_default="$2"
	if [ -z "${_arg}" ]; then
		if is_tty; then
			prompt_val _arg "Directory" "${_default}"
		else
			_arg="${_default}"
		fi
	fi
	case "${_arg}" in
		/*) printf '%s\n' "${_arg}" ;;
		*) printf '%s\n' "${DEPLOY_DIR}/${_arg#./}" ;;
	esac
}

cmd_data_export() {
	_de_dir=""
	while [ "$#" -gt 0 ]; do
		case "$1" in
			-*) help_text data export >&2; die "data export: unknown option '$1'" ;;
			*)
				[ -z "${_de_dir}" ] || die "data export: one directory only"
				_de_dir="$1"
				;;
		esac
		shift
	done
	resolve_prod_deploy_dir
	_out="$(data_resolve_dir_arg "${_de_dir}" "${DEPLOY_DIR}/data")"

	_data_mount="$(deploy_env_get LIMEDOC_DATA_MOUNT)"
	_data_mount="${_data_mount:-limedoc_data}"

	if data_is_host_mount "${_data_mount}"; then
		_src="$(data_abs_host_path "${_data_mount}")"
		_src_abs="$(CDPATH= cd -- "${_src}" 2>/dev/null && pwd || true)"
		_out_abs="$(CDPATH= cd -- "${_out}" 2>/dev/null && pwd || true)"
		if [ -n "${_src_abs}" ] && [ "${_src_abs}" = "${_out_abs}" ]; then
			info "export target is the live host data dir — nothing to copy"
			data_write_manifest "${_out}" "host" "${_src}" "${_src}/cache/vectorsearch"
			info "export OK (already at ${_out})"
			return 0
		fi
	fi

	# Volume names come from the running container's mounts: read them before
	# the stop.
	if ! data_is_host_mount "${_data_mount}"; then
		data_resolve_volume_names
	fi
	(umask 077 && mkdir -p "${_out}") || die "cannot create ${_out}"
	data_trap_restart
	data_stop_writers

	if data_is_host_mount "${_data_mount}"; then
		data_cp_host_tree "${_src}" "${_out}"
		data_write_manifest "${_out}" "host" "${_src}" "${_src}/cache/vectorsearch"
	else
		docker volume inspect "${DATA_VOL_NAME}" >/dev/null 2>&1 ||
			die "data volume not found: ${DATA_VOL_NAME} (is the core stack created?)"
		data_cp_volume_to_dir "${DATA_VOL_NAME}" "${_out}"
		(umask 077 && mkdir -p "${_out}/cache/vectorsearch") ||
			die "cannot create ${_out}/cache/vectorsearch"
		if docker volume inspect "${VS_VOL_NAME}" >/dev/null 2>&1; then
			data_cp_volume_to_dir "${VS_VOL_NAME}" "${_out}/cache/vectorsearch"
		else
			info "vectorsearch volume ${VS_VOL_NAME} missing — left empty cache/vectorsearch"
		fi
		data_write_manifest "${_out}" "volumes" "${DATA_VOL_NAME}" "${VS_VOL_NAME}"
	fi
	data_restart_writers
	data_trap_clear
	info "exported unified data tree to ${_out} (readable by its owner only)"
	info "not in the export: the deploy .env and its keys. With CONTENT_VERSION_MODE=encrypted the tree is unreadable without CONTENT_VERSION_GLOBAL_KEY (and the retired keys) — back those up separately"
	info "volume→host: set LIMEDOC_DATA_MOUNT=./data and VECTORSEARCH_CACHE_MOUNT=./data/cache/vectorsearch (or this path), then ldcmd up"
}

cmd_data_import() {
	_di_dir=""
	_di_yes=0
	_di_backup=1
	while [ "$#" -gt 0 ]; do
		case "$1" in
			--yes|-y) _di_yes=1 ;;
			--no-backup) _di_backup=0 ;;
			-*) help_text data import >&2; die "data import: unknown option '$1'" ;;
			*)
				[ -z "${_di_dir}" ] || die "data import: one directory only"
				_di_dir="$1"
				;;
		esac
		shift
	done
	resolve_prod_deploy_dir
	_src="$(data_resolve_dir_arg "${_di_dir}" "${DEPLOY_DIR}/data")"
	data_validate_import_source "${_src}"

	_data_mount="$(deploy_env_get LIMEDOC_DATA_MOUNT)"
	_data_mount="${_data_mount:-limedoc_data}"
	if data_is_host_mount "${_data_mount}"; then
		die "LIMEDOC_DATA_MOUNT=${_data_mount} is already a host path. Set mounts to named volumes (limedoc_data / limedoc_vectorsearch_cache), recreate, then re-run import — or copy files into the host dir directly."
	fi

	data_resolve_volume_names

	info "import replaces ALL content of volume ${DATA_VOL_NAME} (documents, uploads, history, ACLs, config) and of ${VS_VOL_NAME} with ${_src}"
	if [ "${_di_backup}" = "1" ]; then
		info "the current ${DATA_VOL_NAME} is copied to a snapshot volume first (needs the same disk space again; --no-backup skips it)"
	else
		info "--no-backup: the current content is NOT kept"
	fi
	if [ "${_di_yes}" != "1" ]; then
		is_tty ||
			die "data import replaces the live data volume; re-run with --yes to confirm (non-interactive)"
		ask_yes_no "Replace the data of this instance (${DEPLOY_DIR})?" n ||
			die "data import cancelled; nothing was changed"
	fi

	data_trap_restart
	data_stop_writers

	docker volume create "${DATA_VOL_NAME}" >/dev/null 2>&1 || true
	docker volume create "${VS_VOL_NAME}" >/dev/null 2>&1 || true

	_di_snap=""
	if [ "${_di_backup}" = "1" ]; then
		if data_volume_has_content "${DATA_VOL_NAME}"; then
			_di_snap="${DATA_VOL_NAME}-pre-import-$(date -u +%Y%m%dT%H%M%SZ)"
			data_snapshot_volume "${DATA_VOL_NAME}" "${_di_snap}"
		else
			info "volume ${DATA_VOL_NAME} is empty — no snapshot needed"
		fi
	fi

	if [ -n "${_di_snap}" ]; then
		DATA_RESTART_HOLD="the import did not finish and ${DATA_VOL_NAME} is incomplete. Re-run the import, or restore the snapshot volume ${_di_snap} (docker run --rm -v ${_di_snap}:/from:ro -v ${DATA_VOL_NAME}:/to ${LDCMD_HELPER_IMAGE} sh -c 'find /to -mindepth 1 -maxdepth 1 -exec rm -rf {} +; cp -a /from/. /to/'), then ldcmd up"
	else
		DATA_RESTART_HOLD="the import did not finish and ${DATA_VOL_NAME} is incomplete. Re-run the import, then ldcmd up"
	fi
	data_cp_dir_to_volume "${_src}" "${DATA_VOL_NAME}"
	if [ -d "${_src}/cache/vectorsearch" ]; then
		data_cp_dir_to_volume "${_src}/cache/vectorsearch" "${VS_VOL_NAME}"
	else
		# An index of the previous data must not outlive it.
		info "no cache/vectorsearch in ${_src} — volume ${VS_VOL_NAME} is emptied (the worker rebuilds the search index)"
		_di_empty="$(mktemp -d)" || die "mktemp failed"
		data_cp_dir_to_volume "${_di_empty}" "${VS_VOL_NAME}"
		rmdir "${_di_empty}" 2>/dev/null || true
	fi
	DATA_RESTART_HOLD=""

	info "imported ${_src} into volumes ${DATA_VOL_NAME} + ${VS_VOL_NAME}"
	if [ -n "${_di_snap}" ]; then
		info "previous data: snapshot volume ${_di_snap} — remove it once the import is confirmed good: docker volume rm ${_di_snap}"
	fi
	info "not part of an import: the deploy .env and its keys. An encrypted tree (CONTENT_VERSION_MODE=encrypted) needs the key it was written with in this instance's .env"
	data_restart_writers
	data_trap_clear
	info "Redis still holds caches of the previous data: with the app running (ldcmd up), run ldcmd admin rebuild"
}

pack_dev_sidecar_up() {
	[ "${PACK_KIND}" = "plugin" ] || return 0
	[ -f "deploy.json" ] || return 0
	command -v python3 >/dev/null 2>&1 || return 0
	_files="$(python3 - <<'PY'
import json
m=json.load(open("deploy.json", encoding="utf-8"))
for f in m.get("composeFiles") or []:
    print(f)
PY
)"
	[ -n "${_files}" ] || return 0
	_net="$(grep -E '^DOCKER_NETWORK_NAME=' .env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true)"
	if [ -z "${_net}" ]; then
		_snake="$(echo "${PACK_ID}" | tr '-' '_')"
		_net="limedoc_${_snake}_dev"
	fi
	export DOCKER_NETWORK_NAME="${_net}"
	_args="--project-name limedoc-dev-sidecar-${PACK_ID} --env-file .env"
	_has=0
	for _rel in ${_files}; do
		[ -f "${_rel}" ] || continue
		_args="${_args} -f ${_rel}"
		_has=1
	done
	[ "${_has}" = "1" ] || return 0
	for _pub in $(sidecar_publish_files "$(pwd)" 2>/dev/null); do
		_args="${_args} -f ${_pub}"
	done
	info "pack-dev sidecar up (network ${_net})"
	# shellcheck disable=SC2086
	docker compose ${_args} up -d --build || info "pack-dev sidecar up failed"
}

pack_dev_sidecar_down() {
	[ "${PACK_KIND}" = "plugin" ] || return 0
	docker compose --project-name "limedoc-dev-sidecar-${PACK_ID}" down 2>/dev/null || true
}

# wait_app_healthy — poll /api/health on APP_HOST_PORT (deploy .env, default
# 8000) for up to two minutes. Run from the deploy dir.
wait_app_healthy() {
	_wh_port="$(grep -E '^APP_HOST_PORT=' .env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true)"
	_wh_url="http://127.0.0.1:${_wh_port:-8000}/api/health"
	_wh_max="${LDCMD_HEALTH_TIMEOUT_SECS:-120}"
	step "waiting for the app to answer ${_wh_url} (up to ${_wh_max}s)"
	_wh_t0="$(now_secs)"
	_wh_next="${LDCMD_HEARTBEAT_SECS}"
	while :; do
		# Bounded: a booting app can accept the connection and answer late.
		if curl -sf --connect-timeout 3 --max-time 5 "${_wh_url}" >/dev/null 2>&1; then
			info "    app healthy after $(($(now_secs) - _wh_t0))s"
			return 0
		fi
		_wh_s=$(($(now_secs) - _wh_t0))
		if [ "${_wh_s}" -ge "${_wh_max}" ]; then
			info "    no healthy answer after ${_wh_s}s"
			info "    app logs: cd ${DEPLOY_DIR:-.} && docker compose logs --tail 100 app"
			return 1
		fi
		if [ "${_wh_s}" -ge "${_wh_next}" ]; then
			info "    … still starting (${_wh_s}s; boot migrations and pack loading can take a while)"
			_wh_next=$((_wh_next + LDCMD_HEARTBEAT_SECS))
		fi
		sleep 2
	done
}

cmd_bootstrap() {
	_bs_force=0
	_bs_insecure_redis="${LDCMD_ALLOW_INSECURE_REDIS:-0}"
	while [ $# -gt 0 ]; do
		case "$1" in
			--force) _bs_force=1 ;;
			--allow-insecure-redis) _bs_insecure_redis=1 ;;
			*) die "bootstrap: unknown argument '$1' (--force|--allow-insecure-redis)" ;;
		esac
		shift
	done
	BOOTSTRAP_CWD="$(pwd)"
	resolve_bootstrap_deploy_dir
	LIMEDOC_IMAGE="${LIMEDOC_IMAGE:-${DEFAULT_LIMEDOC_IMAGE}}"
	LIMEDOC_VERSION="${LIMEDOC_VERSION:-}"
	if [ -z "${LIMEDOC_VERSION}" ]; then
		LIMEDOC_VERSION="$(image_tag "${LIMEDOC_IMAGE}")"
	fi
	LIMEDOC_VERSION="$(echo "${LIMEDOC_VERSION}" | sed 's/^v//')"
	# Becomes part of the bundle URL and file name: semver or a channel alias.
	printf '%s\n' "${LIMEDOC_VERSION}" |
		grep -Eq '^([0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?|latest|edge)$' ||
		die "invalid LIMEDOC_VERSION '${LIMEDOC_VERSION}' (semver, latest or edge)"

	command -v docker >/dev/null 2>&1 || die "docker required for bootstrap"
	docker compose version >/dev/null 2>&1 || die "docker compose plugin required"
	command -v curl >/dev/null 2>&1 || die "curl required"
	command -v unzip >/dev/null 2>&1 || die "unzip required"

	info "deploy directory: ${DEPLOY_DIR}"
	check_bootstrap_target_dir "${DEPLOY_DIR}" "${_bs_force}"
	mkdir -p "${DEPLOY_DIR}"
	# Every later step of bootstrap works on this new instance, whatever
	# `ldcmd use` has selected.
	export LIMEDOC_DEPLOY_DIR="${DEPLOY_DIR}"
	export LDCMD_INSTANCE_SOURCE="bootstrap"
	cd "${DEPLOY_DIR}" || die "cannot cd ${DEPLOY_DIR}"

	BASE="${DEFAULT_PACKAGE_REGISTRY_URL}/api/packages/${DEFAULT_DEPLOY_BUNDLE_OWNER}/generic/${DEFAULT_DEPLOY_BUNDLE_PACKAGE}/${LIMEDOC_VERSION}"
	ZIP="${DEFAULT_DEPLOY_BUNDLE_ARTIFACT}-${LIMEDOC_VERSION}.zip"
	fetch_deploy_bundle "${BASE}" "${ZIP}" "${LIMEDOC_VERSION}"
	# Unpacked in a staging dir, then copied in: the size check must not
	# count what an existing deploy dir already holds (a data directory).
	_bs_stage="$(mktemp -d)" || die "mktemp failed"
	safe_unzip "${ZIP}" "${_bs_stage}" "${LDCMD_BUNDLE_MAX_EXTRACT_BYTES}" -q || {
		rm -rf "${_bs_stage}"
		rm -f "${ZIP}"
		die "cannot extract the deploy bundle ${ZIP}"
	}
	rm -f "${ZIP}"
	# The verified bundle names the app image it was released with.
	BUNDLE_IMAGE_DIGEST=""
	bundle_image_digest "${_bs_stage}"
	rm -f "${_bs_stage}/${BUNDLE_DIGEST_FILE}"
	cp -R "${_bs_stage}/." "${DEPLOY_DIR}/" || {
		rm -rf "${_bs_stage}"
		die "cannot copy the deploy bundle into ${DEPLOY_DIR}"
	}
	rm -rf "${_bs_stage}"
	if [ -n "${BUNDLE_IMAGE_DIGEST}" ]; then
		LIMEDOC_IMAGE="$(image_repo "${LIMEDOC_IMAGE}"):${LIMEDOC_VERSION}@${BUNDLE_IMAGE_DIGEST}"
		info "app image pinned by the signed bundle: ${LIMEDOC_IMAGE}"
	fi

	# Optional previous deploy env file (any name; paths relative to BOOTSTRAP_CWD).
	RESTORE_ENV=0
	if is_tty; then
		info "Restore: provide a previous deploy env file to reuse as questionnaire defaults."
		info "Any filename works (copied to deploy .env). Relative paths use the directory where ldcmd was started."
		info "Crypto settings from that file are kept (CONTENT_VERSION_* are not changed)."
		prompt_val _prev_env "Path to previous deploy env file (empty = new install)" ""
		if [ -n "${_prev_env}" ]; then
			_prev_env="$(resolve_prev_env_path "${_prev_env}")"
			[ -f "${_prev_env}" ] ||
				die "previous env file not found: ${_prev_env} (relative paths use ${BOOTSTRAP_CWD})"
			[ -r "${_prev_env}" ] || die "previous env file not readable: ${_prev_env}"
			cp -f "${_prev_env}" "${DEPLOY_DIR}/.env" ||
				die "failed to copy ${_prev_env} → ${DEPLOY_DIR}/.env"
			RESTORE_ENV=1
			info "copied ${_prev_env} → ${DEPLOY_DIR}/.env (secrets kept; not printed)"
		fi
	fi

	info "running questionnaire in ${LIMEDOC_IMAGE}"
	if ! docker pull "${LIMEDOC_IMAGE}"; then
		info "pull failed — try: docker login git.belowtoxic.cloud"
		if [ -n "${BUNDLE_IMAGE_DIGEST}" ]; then
			info "the signed bundle pins ${BUNDLE_IMAGE_DIGEST}: a mirror must hold the image unchanged; LDCMD_PIN_IMAGE_DIGEST=0 pulls by tag instead"
		fi
		docker pull "${LIMEDOC_IMAGE}" || die "cannot pull ${LIMEDOC_IMAGE}"
	fi
	_host_deploy_parent="$(dirname "${DEPLOY_DIR}")"
	_compose_proj="$(prod_compose_project_name)"
	_restore_env_docker=
	if [ "${RESTORE_ENV}" = "1" ]; then
		_restore_env_docker="-e LIMEDOC_RESTORE_ENV=1"
	fi
	# shellcheck disable=SC2086
	docker run --rm -it --network host \
		--user "$(id -u):$(id -g)" \
		-v "${DEPLOY_DIR}:/host-deploy" \
		-e LIMEDOC_HOST_DEPLOY=/host-deploy \
		-e LIMEDOC_HOST_DEPLOY_PARENT="${_host_deploy_parent}" \
		-e LIMEDOC_COMPOSE_PROJECT="${_compose_proj}" \
		-e LIMEDOC_BOOTSTRAP=1 \
		${_restore_env_docker} \
		"${LIMEDOC_IMAGE}" \
		deno task setup:bootstrap || die "questionnaire failed"

	[ -f bootstrap.meta.json ] || die "missing bootstrap.meta.json"
	[ -f .env ] || die "missing .env after questionnaire"

	# Flat deploy layout: service env_file must be adjacent .env (not ../.env).
	export LIMEDOC_ENV_FILE=.env

	# The questionnaire wrote LIMEDOC_IMAGE by tag. Pin it to the image the
	# signed bundle names when it is that release; another version, or a
	# digest the operator set, is left alone.
	if [ -n "${BUNDLE_IMAGE_DIGEST}" ]; then
		_bs_env_image="$(deploy_env_get LIMEDOC_IMAGE)"
		if [ -z "${_bs_env_image}" ]; then
			info "WARNING: .env sets no LIMEDOC_IMAGE; the compose default is pulled by tag"
		elif [ -n "$(image_digest "${_bs_env_image}")" ]; then
			info "LIMEDOC_IMAGE in .env is pinned by digest already; left as it is"
		elif [ "$(image_tag "${_bs_env_image}")" = "${LIMEDOC_VERSION}" ]; then
			_bs_pinned="$(image_repo "${_bs_env_image}"):${LIMEDOC_VERSION}@${BUNDLE_IMAGE_DIGEST}"
			set_deploy_env LIMEDOC_IMAGE "${_bs_pinned}"
			info "LIMEDOC_IMAGE=${_bs_pinned} (digest from the signed bundle)"
		else
			info "WARNING: LIMEDOC_IMAGE=${_bs_env_image} is not the release of this deploy bundle (${LIMEDOC_VERSION}): it is pulled by its tag. Pin it with: ldcmd update --version <that version>"
		fi
	fi

	ensure_host_data_mounts
	seed_docker_network_name

	_proj="$(prod_compose_project_name)"
	COMPOSE_ARGS="--project-directory ${DEPLOY_DIR} --project-name ${_proj} -f docker-compose.yml -f docker-compose.registry.yml --env-file .env"
	if grep -q '"mode": "external"' bootstrap.meta.json 2>/dev/null || \
		grep -q '"mode":"external"' bootstrap.meta.json 2>/dev/null; then
		COMPOSE_ARGS="${COMPOSE_ARGS} -f docker-compose.wizard.publish.yml"
	fi
	PROFILE_ARGS=""
	for p in redis app; do
		if grep -q "\"${p}\"" bootstrap.meta.json 2>/dev/null; then
			PROFILE_ARGS="${PROFILE_ARGS} --profile ${p}"
		fi
	done
	[ -z "${PROFILE_ARGS}" ] && PROFILE_ARGS="--profile redis --profile app"

	step "pulling images"
	# shellcheck disable=SC2086
	if ! run_long "image pull" docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} pull; then
		info "pull failed — try: docker login git.belowtoxic.cloud"
		# shellcheck disable=SC2086
		docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} pull || die "compose pull failed"
	fi
	step "starting containers"
	# shellcheck disable=SC2086
	run_long "compose up" docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} up -d ||
		die "compose up failed"
	register_instance "${DEPLOY_DIR}"
	if [ -z "$(selected_instance_dir)" ]; then
		mkdir -p "${LDCMD_STATE_DIR}" &&
			canon_dir "${DEPLOY_DIR}" > "${LDCMD_STATE_DIR}/current" &&
			info "selected instance $(instance_id "${DEPLOY_DIR}") for later ldcmd commands (ldcmd list / ldcmd use)"
	else
		info "instance $(instance_id "${DEPLOY_DIR}") registered; work on it with: ldcmd use $(instance_id "${DEPLOY_DIR}")"
	fi

	_packs_restored=0
	_packs_wiped=0
	_reg_count="$(registry_pack_count)"
	_reg_count="${_reg_count:-0}"
	if [ "${_reg_count}" -gt 0 ] 2>/dev/null; then
		info "— Packs (install registry) —"
		info "Host data lists ${_reg_count} pack(s) in config/installed-packs.json."
		info "Pack bytes live in separate Docker volumes (often empty on a new deploy)."
		info "Missing skins/templates (e.g. lime, email) cause PackReloadTrustError crash loops."
		_do_restore=1
		if is_tty; then
			printf "Restore %s pack(s) from install registry now? [Y/n]: " "${_reg_count}" >&2
			read -r _ans || true
			case "${_ans:-Y}" in
				n|N|no|No) _do_restore=0 ;;
			esac
		fi
		if [ "${_do_restore}" = "1" ]; then
			_restore_st=0
			run_packs_restore_in_app --force || _restore_st=$?
			if [ "${_restore_st}" -eq 0 ]; then
				_packs_restored=1
				info "recreating app after pack restore"
				# shellcheck disable=SC2086
				docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} up -d || true
			elif pack_volumes_look_populated; then
				_packs_restored=1
				info "pack restore reported errors, but pack volumes look populated (partial success)."
				info "retry remaining packs later: ldcmd packs restore --force"
				info "recreating app after partial pack restore"
				# shellcheck disable=SC2086
				docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} up -d || true
			else
				info "pack restore failed and pack volumes still look empty"
				info "fix store access (trust registry / package registry), then: ldcmd packs restore --force"
				info "or wipe the registry (archives config first) and install recommended packs"
				if is_tty; then
					printf "Wipe install registry (and empty pack volumes) instead? [y/N]: " >&2
					read -r _wipe_ans || true
					case "${_wipe_ans:-N}" in
						y|Y|yes|Yes)
							archive_data_config_for_wipe &&
								wipe_install_registry_and_pack_volumes &&
								_packs_wiped=1
							# shellcheck disable=SC2086
							docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} up -d || true
							;;
					esac
				fi
			fi
		else
			if is_tty; then
				printf "Wipe install registry (archives data/config first)? [y/N]: " >&2
				read -r _wipe_ans || true
				case "${_wipe_ans:-N}" in
					y|Y|yes|Yes)
						archive_data_config_for_wipe &&
							wipe_install_registry_and_pack_volumes &&
							_packs_wiped=1
						# shellcheck disable=SC2086
						docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} up -d || true
						;;
					*)
						info "leaving registry as-is — app may crash until: ldcmd packs restore --force"
						;;
				esac
			fi
		fi
	fi

	wait_app_healthy ||
		info "app health check timed out — continuing; packs may fail"

	# Redis auth before any sidecar starts (their composes need the URLs).
	info "— Redis auth —"
	redis_secure_or_stop "${_bs_insecure_redis}" || true

	if [ "${_packs_restored}" = "1" ]; then
		info "— Sidecars —"
		info "Configuring pack sidecars (Collabora / workers) against deploy .env…"
		if DEPLOY_DIR="${DEPLOY_DIR}" cmd_sidecar_up --configure; then
			info "recreating core + sidecars so the app picks up configure .env (ldcmd up)"
			DEPLOY_DIR="${DEPLOY_DIR}" cmd_prod_up ||
				info "ldcmd up failed — retry: ldcmd up"
		else
			info "sidecar configure/up failed — run: ldcmd sidecar up --configure && ldcmd up"
		fi
	elif [ "${_packs_wiped}" = "1" ] || [ "${_reg_count}" = "0" ]; then
		if is_tty; then
			info "— Plugins —"
			info "Plugins, skins, and templates are registry packs (not in the core deploy zip)."
			info "Some plugins ship sidecars: pack-owned Compose workers (Collabora, web-render, vectorsearch, …)."
			info "After installing packs: ldcmd sidecar up [--configure] for workers that declare deploy.json."
			info "Install alone often does not recreate the app — finish with: ldcmd up (picks up .env / mounts)."
			printf "Install recommended packs into volumes now? [Y/n]: " >&2
			read -r _ans || true
			case "${_ans:-Y}" in
				n|N|no|No) info "skipping packs" ;;
				*)
					info "installing recommended packs (compose exec)"
					# shellcheck disable=SC2086
					if ! docker compose ${COMPOSE_ARGS} ${PROFILE_ARGS} exec -T app \
						deno task packs:install -- --recommended; then
						info "pack install failed (check PACK_SIG_MISSING / registry .sig.json uploads; retry: docker compose exec app deno task packs:install -- --recommended)"
					else
						info "starting pack sidecars (ldcmd sidecar up --configure)"
						if DEPLOY_DIR="${DEPLOY_DIR}" cmd_sidecar_up --configure; then
							info "recreating core + sidecars so the app picks up configure .env (ldcmd up)"
							DEPLOY_DIR="${DEPLOY_DIR}" cmd_prod_up ||
								info "ldcmd up failed — retry: ldcmd up"
						else
							info "sidecar up failed — run: ldcmd sidecar up --configure && ldcmd up"
						fi
					fi
					;;
			esac
		fi
	else
		info "skipping recommended packs (registry restore not completed; volumes still empty)"
		info "retry: ldcmd packs restore --force"
	fi

	info "bootstrap complete in ${DEPLOY_DIR}"
	info "later packs: ldcmd plugin install … → ldcmd sidecar up --configure → ldcmd up"
	info "packs restore: ldcmd packs restore --force"
	info "check .env APP_BASE_* then: curl -sf http://127.0.0.1:\${APP_HOST_PORT:-8000}/api/health"
}

# ── updates ───────────────────────────────────────────────────────────────────

# semver_cmp <a> <b> → prints -1, 0 or 1 (core numbers; a pre-release sorts
# before its release). Non-semver input compares as equal.
semver_cmp() {
	awk -v a="$1" -v b="$2" 'BEGIN {
		na = split(a, x, "-"); nb = split(b, y, "-")
		split(x[1], p, "."); split(y[1], q, ".")
		for (i = 1; i <= 3; i++) {
			if (p[i] + 0 < q[i] + 0) { print -1; exit }
			if (p[i] + 0 > q[i] + 0) { print 1; exit }
		}
		if (na > 1 && nb == 1) { print -1; exit }
		if (na == 1 && nb > 1) { print 1; exit }
		print 0
	}'
}

is_semver() {
	printf '%s\n' "$1" |
		grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$'
}

LDCMD_REPO_API="${DEFAULT_PACKAGE_REGISTRY_URL}/api/v1/repos/limedoc/ldcmd"
LDCMD_PACKAGE_BASE="${DEFAULT_PACKAGE_REGISTRY_URL}/api/packages/limedoc/generic/ldcmd"

# Newest published ldcmd release (Forgejo "latest release", not a draft or
# pre-release), without the v prefix.
latest_ldcmd_version() {
	ld_curl "${LDCMD_META_MAX_BYTES}" -fsSL "${LDCMD_REPO_API}/releases/latest" 2>/dev/null |
		sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"v\{0,1\}\([^"]*\)".*/\1/p' |
		head -1
}

# Absolute path of the running ldcmd script.
ldcmd_self_path() {
	case "$0" in
		*/*) _sp="$0" ;;
		*) _sp="$(command -v "$0" 2>/dev/null || true)" ;;
	esac
	[ -n "${_sp}" ] && [ -f "${_sp}" ] || return 1
	printf '%s/%s\n' "$(CDPATH= cd -- "$(dirname "${_sp}")" && pwd)" \
		"$(basename "${_sp}")"
}

# ldcmd self-update [--check] [--version X.Y.Z] [--force]
# Replaces this script with a signed ldcmd release (same checks as install.sh:
# sha256 + Ed25519 statement for artifact ldcmd, channel release).
cmd_self_update() {
	_su_check=0
	_su_force=0
	_su_ver=""
	while [ $# -gt 0 ]; do
		case "$1" in
			--check|--dry-run) _su_check=1; shift ;;
			--force) _su_force=1; shift ;;
			--version|-v)
				[ $# -ge 2 ] || die "self-update: --version needs a value"
				_su_ver="${2#v}"; shift 2 ;;
			*) die "self-update: unknown argument '$1' (--check|--version X.Y.Z|--force)" ;;
		esac
	done
	command -v curl >/dev/null 2>&1 || die "curl required"
	_su_self="$(ldcmd_self_path)" || die "self-update: cannot locate the running ldcmd"
	_su_dir="$(dirname "${_su_self}")"
	[ ! -d "${_su_dir}/.git" ] ||
		die "self-update: ${_su_self} is a git checkout; use git pull instead"

	if [ -z "${_su_ver}" ]; then
		_su_ver="$(latest_ldcmd_version)"
		[ -n "${_su_ver}" ] || die "self-update: cannot read the latest release from ${LDCMD_REPO_API}"
		_su_explicit=0
	else
		_su_explicit=1
	fi
	is_semver "${_su_ver}" || die "self-update: invalid version '${_su_ver}'"
	_su_cmp="$(semver_cmp "${_su_ver}" "${LDCMD_VERSION}")"
	if [ "${_su_cmp}" = "0" ] && [ "${_su_force}" != "1" ]; then
		info "ldcmd ${LDCMD_VERSION} is up to date"
		return 0
	fi
	if [ "${_su_cmp}" = "-1" ] && [ "${_su_explicit}" != "1" ]; then
		info "ldcmd ${LDCMD_VERSION} is newer than the latest release ${_su_ver}; nothing to do"
		return 0
	fi
	if [ "${_su_check}" = "1" ]; then
		info "ldcmd update available: ${LDCMD_VERSION} → ${_su_ver} (run: ldcmd self-update)"
		return 0
	fi
	[ -w "${_su_dir}" ] ||
		die "self-update: ${_su_dir} is not writable (re-run with rights to it, or reinstall with install.sh)"
	command -v unzip >/dev/null 2>&1 || die "unzip required"

	_su_tmp="$(mktemp -d)"
	# shellcheck disable=SC2064
	trap "rm -rf '${_su_tmp}'" EXIT
	_su_base="${LDCMD_PACKAGE_BASE}/${_su_ver}"
	_su_zip="ldcmd-${_su_ver}.zip"
	info "downloading ldcmd ${_su_ver}"
	ld_download "${LDCMD_BUNDLE_MAX_BYTES}" "${_su_base}/${_su_zip}" "${_su_tmp}/${_su_zip}" ||
		die "self-update: download failed: ${_su_base}/${_su_zip}"
	ld_download "${LDCMD_META_MAX_BYTES}" "${_su_base}/ldcmd-${_su_ver}.sha256" "${_su_tmp}/zip.sha256" ||
		die "self-update: checksum download failed"
	verify_sha256_file "${_su_tmp}/${_su_zip}" "${_su_tmp}/zip.sha256"
	_su_rc=0
	fetch_optional "${_su_base}/ldcmd-${_su_ver}.sig.json" "${_su_tmp}/sig.json" ||
		_su_rc=$?
	case "${_su_rc}" in
		0)
			verify_release_signature "${_su_tmp}/${_su_zip}" "${_su_tmp}/sig.json" \
				ldcmd release "${_su_ver}"
			;;
		2)
			[ "${LDCMD_REQUIRE_SIGNATURE:-${LDCMD_REQUIRE_SIGNATURE_DEFAULT}}" = "0" ] ||
				die "self-update: no release signature published for ldcmd ${_su_ver}"
			info "WARNING: no release signature for ldcmd ${_su_ver}; checked against the same-origin .sha256 only"
			;;
		*) die "self-update: signature download failed" ;;
	esac
	safe_unzip "${_su_tmp}/${_su_zip}" "${_su_tmp}/x" \
		"${LDCMD_BUNDLE_MAX_EXTRACT_BYTES}" -q ||
		die "self-update: cannot extract ${_su_zip}"
	_su_new="$(find "${_su_tmp}/x" -name ldcmd -type f 2>/dev/null | head -1)"
	[ -n "${_su_new}" ] || die "self-update: ldcmd not found in ${_su_zip}"
	sh -n "${_su_new}" || die "self-update: downloaded ldcmd does not parse"
	printf '%s\n' "${_su_ver}" > "${_su_tmp}/ldcmd.VERSION"

	# Rename into place: the running shell keeps reading the old inode.
	cp "${_su_new}" "${_su_self}.new.$$" &&
		chmod 755 "${_su_self}.new.$$" &&
		cp "${_su_tmp}/ldcmd.VERSION" "${_su_dir}/ldcmd.VERSION.new.$$" ||
		die "self-update: cannot write to ${_su_dir}"
	mv -f "${_su_dir}/ldcmd.VERSION.new.$$" "${_su_dir}/ldcmd.VERSION"
	mv -f "${_su_self}.new.$$" "${_su_self}"
	info "updated ${_su_self}: ${LDCMD_VERSION} → ${_su_ver}"
}

# Files of the deploy bundle that `ldcmd update` replaces. Everything else in
# the deploy dir (.env, overlays, sidecars/, data) belongs to the operator.
DEPLOY_BUNDLE_FILES="docker-compose.yml docker-compose.registry.yml docker-compose.publish.yml cool-seccomp-profile.json README.md env.example"

# image_repo / image_tag <ref> — split a container image ref at its tag
# (a registry port is not a tag). A digest (repo:tag@sha256:…) is not part
# of either: the tag keeps saying which release or channel the instance
# follows, the digest says which image exactly.
image_repo() {
	_ir="${1%%@*}"
	case "${_ir##*/}" in
		*:*) printf '%s\n' "${_ir%:*}" ;;
		*) printf '%s\n' "${_ir}" ;;
	esac
}
image_tag() {
	_it="${1%%@*}"
	case "${_it##*/}" in
		*:*) printf '%s\n' "${_it##*:}" ;;
		*) printf 'latest\n' ;;
	esac
}
# image_digest <ref> — the sha256:… of a digest reference, else empty.
image_digest() {
	case "$1" in
		*@*) printf '%s\n' "${1##*@}" ;;
		*) printf '\n' ;;
	esac
}

# The signed deploy bundle names the registry digest of the app image it was
# released with (one line, sha256:<64 hex>), so the signature covers the
# image and not only the compose templates.
BUNDLE_DIGEST_FILE="image.digest"

valid_image_digest() {
	case "$1" in
		sha256:*) ;;
		*) return 1 ;;
	esac
	_vd="${1#sha256:}"
	case "${_vd}" in
		""|*[!a-f0-9]*) return 1 ;;
	esac
	[ "${#_vd}" -eq 64 ]
}

# bundle_image_digest <unpacked bundle dir>: sets BUNDLE_IMAGE_DIGEST (empty
# with a warning for bundles from before the digest was recorded, or when
# LDCMD_PIN_IMAGE_DIGEST=0). Dies on a digest file that is not well-formed.
bundle_image_digest() {
	BUNDLE_IMAGE_DIGEST=""
	_bd_file="$1/${BUNDLE_DIGEST_FILE}"
	if [ ! -e "${_bd_file}" ] && [ ! -L "${_bd_file}" ]; then
		info "WARNING: this deploy bundle names no image digest (released before digests were recorded): the app image is pulled by its tag, which the signature does not cover"
		return 0
	fi
	[ -f "${_bd_file}" ] && [ ! -L "${_bd_file}" ] ||
		die "${BUNDLE_DIGEST_FILE} in the deploy bundle is not a regular file"
	[ "$(wc -l < "${_bd_file}" | tr -d ' ')" -le 1 ] ||
		die "malformed ${BUNDLE_DIGEST_FILE} in the deploy bundle (more than one line)"
	_bd="$(tr -d '\r\n' < "${_bd_file}")"
	valid_image_digest "${_bd}" ||
		die "malformed ${BUNDLE_DIGEST_FILE} in the deploy bundle (want sha256:<64 hex digits>)"
	if [ "${LDCMD_PIN_IMAGE_DIGEST:-1}" = "0" ]; then
		info "WARNING: LDCMD_PIN_IMAGE_DIGEST=0: the image digest of the signed bundle (${_bd}) is ignored; the app image is pulled by its tag"
		return 0
	fi
	BUNDLE_IMAGE_DIGEST="${_bd}"
}

# set_deploy_env <key> <value> — replace KEY=… in the deploy env file, or
# append it.
set_deploy_env() {
	_se_envf="$(deploy_env_file)"
	if grep -qE "^$1=" "${_se_envf}" 2>/dev/null; then
		# A new file next to the old one (private from the start: it holds
		# the secrets of .env) with the old owner and mode, renamed over it:
		# a reader never sees a half-written .env. Key and value reach awk
		# through the environment (awk -v would read backslash escapes).
		if [ -L "${_se_envf}" ]; then
			# Replace the file the link points at, not the link.
			_se_real="$(readlink -f "${_se_envf}" 2>/dev/null || true)"
			[ -n "${_se_real}" ] && [ -f "${_se_real}" ] ||
				die "cannot resolve the symbolic link ${_se_envf}"
			_se_envf="${_se_real}"
		fi
		_se_tmp="$(umask 077 && mktemp "${_se_envf}.ldcmd.XXXXXX")" ||
			die "cannot create a temporary file next to ${_se_envf}"
		if ! LD_K="$1" LD_V="$2" awk 'BEGIN { done = 0; k = ENVIRON["LD_K"]; v = ENVIRON["LD_V"] }
			!done && index($0, k "=") == 1 { print k "=" v; done = 1; next }
			{ print }' "${_se_envf}" > "${_se_tmp}"; then
			rm -f "${_se_tmp}"
			die "cannot rewrite ${_se_envf}"
		fi
		chown "$(env_file_owner "${_se_envf}")" "${_se_tmp}" 2>/dev/null || true
		chmod "$(env_file_mode "${_se_envf}")" "${_se_tmp}" 2>/dev/null || true
		mv -f "${_se_tmp}" "${_se_envf}" || {
			rm -f "${_se_tmp}"
			die "cannot replace ${_se_envf}"
		}
	else
		printf '%s=%s\n' "$1" "$2" >> "${_se_envf}"
	fi
}

# Octal mode and uid:gid of a file (GNU and BSD stat).
env_file_mode() {
	stat -c '%a' "$1" 2>/dev/null || stat -f '%Lp' "$1" 2>/dev/null || echo 600
}
env_file_owner() {
	stat -c '%u:%g' "$1" 2>/dev/null || stat -f '%u:%g' "$1" 2>/dev/null ||
		echo "$(id -u):$(id -g)"
}

# ldcmd update [--check] [--version X.Y.Z|latest|edge] [--image REPO] [--with-packs] [--yes]
# Updates the instance in a prod deploy dir: signed deploy bundle (compose
# templates), app image, sidecars; optionally the installed packs.
cmd_update() {
	_up_check=0
	_up_yes=0
	_up_packs=0
	_up_ver=""
	_up_repo=""
	_up_insecure_redis="${LDCMD_ALLOW_INSECURE_REDIS:-0}"
	while [ $# -gt 0 ]; do
		case "$1" in
			--check|--dry-run) _up_check=1; shift ;;
			--allow-insecure-redis) _up_insecure_redis=1; shift ;;
			--yes|-y) _up_yes=1; shift ;;
			--with-packs) _up_packs=1; shift ;;
			--version|-v)
				[ $# -ge 2 ] || die "update: --version needs a value"
				_up_ver="${2#v}"; shift 2 ;;
			--image)
				[ $# -ge 2 ] || die "update: --image needs an image repository"
				_up_repo="$2"; shift 2
				case "${_up_repo##*/}" in
					*:*|*@*) die "update: --image takes a repository without tag (the tag comes from --version or the current one)" ;;
				esac
				case "${_up_repo}" in
					*[!A-Za-z0-9./:_-]*|"") die "update: invalid image repository '${_up_repo}'" ;;
				esac
				;;
			*) die "update: unknown argument '$1' (--check|--version V|--image REPO|--with-packs|--yes|--allow-insecure-redis)" ;;
		esac
	done
	resolve_prod_deploy_dir
	command -v docker >/dev/null 2>&1 || die "docker required"
	command -v curl >/dev/null 2>&1 || die "curl required"
	command -v unzip >/dev/null 2>&1 || die "unzip required"
	resolve_runtime_app_exec

	_up_image="$(deploy_env_get LIMEDOC_IMAGE)"
	_up_image="${_up_image:-${DEFAULT_LIMEDOC_IMAGE}}"
	_up_cur="$(image_tag "${_up_image}")"
	# A pinned version moves to the newest release: the signed latest bundle
	# says which version that is.
	_up_pinned=0
	if [ -n "${_up_ver}" ]; then
		_up_target="${_up_ver}"
	elif is_semver "${_up_cur}"; then
		_up_target=latest
		_up_pinned=1
	else
		_up_target="${_up_cur}"
	fi
	case "${_up_target}" in
		latest|edge) ;;
		*)
			is_semver "${_up_target}" ||
				die "update: image tag '${_up_target}' is not a release; pass --version X.Y.Z|latest|edge"
			;;
	esac
	step "1/6 fetching and verifying the deploy bundle (${_up_target})"
	_up_tmp="$(mktemp -d)"
	# shellcheck disable=SC2064
	trap "rm -rf '${_up_tmp}'" EXIT
	_up_zip="${DEFAULT_DEPLOY_BUNDLE_ARTIFACT}-${_up_target}.zip"
	(
		cd "${_up_tmp}" &&
			fetch_deploy_bundle \
				"${DEFAULT_PACKAGE_REGISTRY_URL}/api/packages/${DEFAULT_DEPLOY_BUNDLE_OWNER}/generic/${DEFAULT_DEPLOY_BUNDLE_PACKAGE}/${_up_target}" \
				"${_up_zip}" "${_up_target}" &&
			printf '%s\n' "${VERIFIED_RELEASE_VERSION:-}" > signed-version &&
			safe_unzip "${_up_zip}" bundle "${LDCMD_BUNDLE_MAX_EXTRACT_BYTES}" -q
	) || die "update: deploy bundle ${_up_target} could not be fetched and verified"
	bundle_image_digest "${_up_tmp}/bundle"
	if [ "${_up_pinned}" = "1" ]; then
		_up_rel="$(cat "${_up_tmp}/signed-version")"
		is_semver "${_up_rel}" ||
			die "update: the latest release has no signed version; pass --version X.Y.Z"
		case "$(semver_cmp "${_up_rel}" "${_up_cur}")" in
			1) _up_target="${_up_rel}" ;;
			0) _up_target="${_up_cur}" ;;
			*)
				info "${_up_cur} is newer than the latest release ${_up_rel}; nothing to update (pass --version to change it)"
				return 0
				;;
		esac
	fi
	_up_new_image="${_up_repo:-$(image_repo "${_up_image}")}:${_up_target}"
	# By digest when the signed bundle names one: the tag stays in the
	# reference (the release or channel this instance follows), the digest
	# decides which image is pulled.
	if [ -n "${BUNDLE_IMAGE_DIGEST}" ]; then
		_up_new_image="${_up_new_image}@${BUNDLE_IMAGE_DIGEST}"
	elif [ -n "$(image_digest "${_up_image}")" ]; then
		info "WARNING: LIMEDOC_IMAGE is pinned by digest now; after this update it is pulled by tag again"
	fi

	# Before anything changes: does the registry have the target image?
	step "2/6 checking that ${_up_new_image} exists in the registry"
	if [ -n "${BUNDLE_IMAGE_DIGEST}" ]; then
		image_check "$(image_repo "${_up_new_image}")@${BUNDLE_IMAGE_DIGEST}"
	else
		image_check "${_up_new_image}"
	fi
	case "${IMAGE_CHECK}" in
		ok) info "    found" ;;
		missing)
			info "    NOT FOUND: ${IMAGE_CHECK_MSG}"
			_up_official="$(image_repo "${DEFAULT_LIMEDOC_IMAGE}")"
			if [ "$(image_repo "${_up_new_image}")" != "${_up_official}" ]; then
				info "    Limedoc releases are published as ${_up_official}; switch to it with:"
				info "      ldcmd update --image ${_up_official}"
			fi
			if [ -n "${BUNDLE_IMAGE_DIGEST}" ]; then
				info "    the signed bundle pins ${BUNDLE_IMAGE_DIGEST}; a mirror must hold the image unchanged (copied, not rebuilt or re-pushed through docker). LDCMD_PIN_IMAGE_DIGEST=0 pulls by tag instead"
			fi
			if [ "${_up_check}" = "1" ]; then
				return 1
			fi
			die "update: nothing was changed (the image ${_up_new_image} does not exist)"
			;;
		*)
			info "    could not check (${IMAGE_CHECK_MSG:-no answer}); the pull will tell"
			info "    private registry? docker login $(printf '%s' "${_up_new_image}" | cut -d/ -f1)"
			;;
	esac

	_up_changed=""
	for _f in ${DEPLOY_BUNDLE_FILES}; do
		[ -f "${_up_tmp}/bundle/${_f}" ] || continue
		cmp -s "${_up_tmp}/bundle/${_f}" "${DEPLOY_DIR}/${_f}" 2>/dev/null ||
			_up_changed="${_up_changed} ${_f}"
	done
	_up_changed="$(echo "${_up_changed}" | xargs)"
	_up_envf="$(deploy_env_file)"
	# Keys env.example knows and .env does not: commented ones are optional
	# (the app's built-in default applies), set ones deserve a look.
	_up_newkeys=""
	_up_setkeys=""
	if [ -f "${_up_tmp}/bundle/env.example" ]; then
		for _k in $(sed -n 's/^#\{0,1\}[[:space:]]*\([A-Z][A-Z0-9_]*\)=.*/\1/p' \
			"${_up_tmp}/bundle/env.example" | sort -u); do
			grep -qE "^#?[[:space:]]*${_k}=" "${_up_envf}" 2>/dev/null && continue
			if grep -qE "^${_k}=" "${_up_tmp}/bundle/env.example"; then
				_up_setkeys="${_up_setkeys} ${_k}"
			else
				_up_newkeys="${_up_newkeys} ${_k}"
			fi
		done
	fi
	_up_newkeys="$(echo "${_up_newkeys}" | xargs)"
	_up_setkeys="$(echo "${_up_setkeys}" | xargs)"

	info "instance update in ${DEPLOY_DIR}"
	if [ -n "${_up_repo}" ] && [ "$(image_repo "${_up_image}")" != "${_up_repo}" ]; then
		info "  image repository: $(image_repo "${_up_image}") → ${_up_repo}"
	fi
	if [ "${_up_new_image}" = "${_up_image}" ]; then
		info "  app image:  ${_up_image} (pulled; the app is recreated if it changed)"
	else
		info "  app image:  ${_up_image} → ${_up_new_image}"
	fi
	info "  bundle:     ${_up_changed:-no file changes}"
	if [ -n "${_up_setkeys}" ]; then
		info "  settings env.example sets that .env lacks (check them): ${_up_setkeys}"
	fi
	if [ -n "${_up_newkeys}" ]; then
		info "  optional settings, built-in defaults apply (described in ${DEPLOY_DIR}/env.example): ${_up_newkeys}"
	fi

	if [ "${_up_check}" = "1" ]; then
		if app_running && app_has_packs_update; then
			info "packs:"
			run_packs_update --check || true
		fi
		return 0
	fi
	if [ "${_up_yes}" != "1" ]; then
		is_tty || die "update: non-interactive; pass --yes to apply"
		ask_yes_no "Apply the update (the app restarts)?" n || {
			info "nothing changed"
			return 0
		}
	fi

	step "3/6 backing up and installing the new bundle files"
	_up_backup="${DEPLOY_DIR}/.ldcmd-backup/update-$(date -u +%Y%m%dT%H%M%SZ)"
	mkdir -p "${_up_backup}"
	cp -p "${_up_envf}" "${_up_backup}/env"
	for _f in ${_up_changed}; do
		if [ -f "${DEPLOY_DIR}/${_f}" ]; then
			cp -p "${DEPLOY_DIR}/${_f}" "${_up_backup}/${_f}"
		fi
	done
	_up_prev_id=""
	_up_cid="$(${COMPOSE_CMD} ps -q "${APP_SERVICE}" 2>/dev/null | head -1 || true)"
	if [ -n "${_up_cid}" ]; then
		_up_prev_id="$(docker inspect --format '{{.Image}}' "${_up_cid}" 2>/dev/null || true)"
	fi
	info "backup: ${_up_backup}${_up_prev_id:+ (previous app image ${_up_prev_id})}"

	for _f in ${_up_changed}; do
		cp "${_up_tmp}/bundle/${_f}" "${DEPLOY_DIR}/${_f}"
	done
	if [ "${_up_new_image}" != "${_up_image}" ]; then
		set_deploy_env LIMEDOC_IMAGE "${_up_new_image}"
		info "    LIMEDOC_IMAGE=${_up_new_image}"
	fi
	[ -z "${_up_changed}" ] || info "    replaced: ${_up_changed}"

	step "4/6 pulling and starting the new app version (redis + app)"
	# In a subshell: a failure must still print the rollback steps below.
	# Sidecars come after the health check; they never decide whether the
	# app update worked.
	if ! (ensure_host_data_mounts && prod_core_up); then
		case "$(deploy_env_get REDIS_ARGS)" in
			*--aclfile*)
				info "if redis did not start because its ACL file is missing: ldcmd redis secure (repairs it)" ;;
		esac
		info "starting the new version failed. To roll back:"
		info "  cp ${_up_backup}/env ${_up_envf}; copy the other files in ${_up_backup} back; ldcmd up"
		if [ -n "${_up_prev_id}" ]; then
			info "  previous app image: ${_up_prev_id}"
		fi
		die "update: the new version did not start"
	fi
	step "5/6 health check"
	if ! wait_app_healthy; then
		info "the app is not healthy after the update. To roll back:"
		info "  cp ${_up_backup}/env ${_up_envf}; copy the other files in ${_up_backup} back"
		if [ -n "${_up_prev_id}" ]; then
			info "  previous app image: ${_up_prev_id} (docker tag it and point LIMEDOC_IMAGE at that tag)"
		fi
		die "update: health check failed"
	fi
	info "app updated and healthy"

	resolve_runtime_app_exec
	_up_warn=""
	# Instances from before 0.4.5 run Redis without auth; current sidecar
	# packs refuse to start without their own Redis user. Secured instances
	# re-run it too: a new app image can change the sidecar users' rules
	# (ACL LOAD, no restart; a no-op when nothing changed).
	if [ -n "$(redis_secure_missing)" ]; then
		step "securing Redis (ldcmd redis secure)"
	else
		step "refreshing Redis users (ldcmd redis secure)"
	fi
	redis_secure_or_stop "${_up_insecure_redis}" ||
		_up_warn="${_up_warn} Redis auth setup failed and --allow-insecure-redis kept the instance running (run: ldcmd redis secure);"
	if [ "${_up_packs}" = "1" ]; then
		step "6/6 updating packs, then starting sidecars"
	else
		step "6/6 starting sidecars"
	fi
	_up_avail=0
	if ! app_has_packs_update; then
		info "this app version has no packs:update; packs were not checked"
	elif [ "${_up_packs}" = "1" ]; then
		_up_st=0
		run_packs_update || _up_st=$?
		# The sidecar up below covers updated sidecars too.
		PACK_FOLLOWUP_SIDECARS=0 pack_update_followups 0
		[ "${_up_st}" -eq 0 ] || _up_warn="${_up_warn} some pack updates failed;"
	else
		run_packs_update --check >/dev/null 2>&1 || true
		_up_avail="$(printf '%s\n' "${PACKS_UPDATE_OUT:-}" | grep -c '^available' || true)"
		# No pack changed, but the app may still run a failed or old build.
		app_restart_followup "" 0
	fi
	_up_side=0
	(cmd_sidecar_up) || _up_side=$?
	[ "${_up_side}" -eq 0 ] || _up_warn="${_up_warn} some sidecars did not start;"
	if [ "${_up_avail}" -gt 0 ]; then
		info "${_up_avail} pack update(s) available: ldcmd update --with-packs (or ldcmd plugin|skin|template update)"
	fi
	if [ -n "${_up_warn}" ]; then
		info "update complete: the app is updated and healthy, but${_up_warn%;}"
		if [ "${_up_side}" -ne 0 ] && [ "${_up_packs}" != "1" ]; then
			info "  sidecars of old pack versions start after a pack update: ldcmd update --with-packs"
		fi
		return 3
	fi
	info "update complete"
}

# image_check <image>: sets IMAGE_CHECK=ok|missing|unknown (+ IMAGE_CHECK_MSG)
# from the registry's manifest, without pulling.
image_check() {
	IMAGE_CHECK_MSG=""
	if _ic_err="$(docker manifest inspect "$1" 2>&1 >/dev/null)"; then
		IMAGE_CHECK=ok
		return 0
	fi
	IMAGE_CHECK_MSG="$(printf '%s\n' "${_ic_err}" | grep . | head -1)"
	case "${_ic_err}" in
		*"manifest unknown"*|*"no such manifest"*|*"not found"*|*"NotFound"*)
			IMAGE_CHECK=missing
			;;
		*) IMAGE_CHECK=unknown ;;
	esac
}

# ── help ──────────────────────────────────────────────────────────────────────
#
# help_text <command> [<sub-command>] — detailed help on stdout; returns 1
# when there is no such topic. `ldcmd <command> [<sub>] --help` and
# `ldcmd help <command> [<sub>]` print it before any instance or pack
# config is resolved, so help works anywhere.

help_text() {
	_ht_cmd="${1:-}"
	_ht_sub="${2:-}"
	case "${_ht_cmd}" in
		install) _ht_cmd=bootstrap ;;
		ls) _ht_cmd=list ;;
	esac
	case "${_ht_cmd} ${_ht_sub}" in
		"list ")
			cat << 'EOF'
usage: ldcmd list

Lists the Limedoc instances on this host, running or not: id, state, image
and deploy dir. * marks the selected instance (ldcmd use). Instances are
found in ldcmd's state dir, in Docker (compose project labels) and under
LDCMD_INSTANCE_SEARCH.
EOF
			;;
		"use ")
			cat << 'EOF'
usage: ldcmd use <id|path>
       ldcmd use
       ldcmd use --clear

Selects the instance every operator command works on (by id from
ldcmd list, or by deploy dir). Without an argument it shows the selection;
--clear (or none) forgets it.

Instance resolution, first match wins:
  -i, --instance <id|path>   this one command
  LIMEDOC_DEPLOY_DIR         environment
  ldcmd use                  the selection
  the current directory, when it is a deploy dir
  the only instance on the host
EOF
			;;
		"bootstrap ")
			cat << 'EOF'
usage: ldcmd bootstrap [--force] [--allow-insecure-redis]
                              (alias: ldcmd install)

Sets up a new instance: downloads the signed limedoc-deploy bundle, runs
the setup wizard, then pulls and starts the stack (docker compose).

Asks for the deploy dir name (under the current directory, default
limedoc). The deploy dir must be new, empty or an existing Limedoc deploy
dir: bootstrap writes the bundle there and, run as root, hands the whole
directory to the container user (UID 10001).

  --force                  use a non-empty directory that is not a deploy
                           dir
  --allow-insecure-redis   keep the instance running when Redis auth could
                           not be set up (default: stop it and fail)

Environment:
  LIMEDOC_DEPLOY_DIR=/abs/path   deploy dir (no prompt)
  LIMEDOC_VERSION=X.Y.Z|latest|edge
                                 app version to install (default latest)
  LDCMD_PIN_IMAGE_DIGEST=0       pull the app image by tag, not by the
                                 digest the signed bundle names
Needs docker with the compose plugin, curl and unzip.
EOF
			;;
		"update ")
			cat << 'EOF'
usage: ldcmd update [--check] [--version X.Y.Z|latest|edge] [--image REPO]
                    [--with-packs] [--yes] [--allow-insecure-redis]

Updates the instance: the signed deploy bundle, the app image and the
pack sidecars. Checks that the image exists before changing anything and
backs up replaced files under .ldcmd-backup/.

The signed bundle names the registry digest of its app image: LIMEDOC_IMAGE
becomes <repo>:<tag>@sha256:… and that exact image is pulled (the tag only
says which release or channel the instance follows). A bundle from before
digests were recorded is pulled by tag, with a warning.
LDCMD_PIN_IMAGE_DIGEST=0 ignores the digest (a mirror that rebuilt the
image).

  --check, --dry-run   only report what would change
  --version V          target app version (default: the LIMEDOC_IMAGE tag,
                       or latest)
  --image REPO         switch the image repository
  --with-packs         also update installed packs to the store versions
  -y, --yes            no questions (required without a TTY)
  --allow-insecure-redis
                       keep the instance running when Redis auth could not
                       be set up or refreshed. Default: the stack (redis +
                       app) is stopped and the update fails; start it with
                       ldcmd up and run ldcmd redis secure.
EOF
			;;
		"self-update ")
			cat << 'EOF'
usage: ldcmd self-update [--check] [--version X.Y.Z] [--force]

Replaces this ldcmd with the latest signed release (or --version).
  --check, --dry-run   only report whether a newer release exists
  --version X.Y.Z      install that release
  --force              reinstall even when already current
EOF
			;;
		"up ")
			cat << 'EOF'
usage: ldcmd up [sidecar-id…]

Deploy dir: starts the core stack (Redis + app), then the pack sidecars
(all installed ones, or the named ones; see ldcmd sidecar up). Recreates
containers whose config changed, so it also applies .env changes.

Pack checkout: starts the pack-dev stack (compose.dev.yml + the pack's
composeFiles); extra arguments go to docker compose up.
EOF
			;;
		"down ")
			cat << 'EOF'
usage: ldcmd down [sidecar-id…]

Deploy dir: stops the pack sidecars (all, or the named ones), then the
core stack. Volumes and data stay.

Pack checkout: stops the pack-dev stack; extra arguments go to
docker compose down.
EOF
			;;
		"status ")
			cat << 'EOF'
usage: ldcmd status

Core services (docker compose ps) and the pack sidecars of the instance.
EOF
			;;
		"data ")
			cat << 'EOF'
usage: ldcmd data export [DIR]
       ldcmd data import [--yes] [--no-backup] [DIR]

Moves instance data between the Docker volumes and a host directory
(default: <deploy dir>/data).
  export   copy limedoc_data and the vectorsearch cache into DIR
  import   replace the content of those two volumes with DIR

Both stop the app and the vectorsearch sidecar for the copy and start
again what was running. The deploy .env and its keys are not part of the
data: back them up separately.

Run ldcmd data <export|import> --help for details.
EOF
			;;
		"data export")
			cat << 'EOF'
usage: ldcmd data export [DIR]

Copies the limedoc_data volume and the vectorsearch cache volume into one
host tree at DIR (default <deploy dir>/data), e.g. for a backup or a move
to another host.

The app and the vectorsearch sidecar are stopped for the copy (the wiki is
down meanwhile) and started again afterwards, also when the copy fails.
Nothing is copied when a writer cannot be stopped.

DIR is created for its owner only (mode 0700): it holds every document and
upload. Not in the export: the deploy .env and its keys. With
CONTENT_VERSION_MODE=encrypted the exported tree is unreadable without
CONTENT_VERSION_GLOBAL_KEY (and CONTENT_VERSION_RETIRED_KEYS) — keep the
keys with the backup, in a separate place.
EOF
			;;
		"data import")
			cat << 'EOF'
usage: ldcmd data import [--yes] [--no-backup] [DIR]

Restores a tree written by ldcmd data export from DIR (default
<deploy dir>/data) into the limedoc_data and vectorsearch cache volumes,
REPLACING their content.

  --yes        do not ask for confirmation (required without a terminal)
  --no-backup  do not snapshot the current data volume first

DIR must be a Limedoc data tree (tree/ documents/ config/ blobs/ blocks/
cache/); when it carries the export manifest, the manifest is checked too.
An empty directory is refused.

The app and the vectorsearch sidecar are stopped first; nothing is changed
when one cannot be stopped. Before the volume is cleared its content is
copied to a snapshot volume <data volume>-pre-import-<UTC time> (needs the
same disk space again; remove it with docker volume rm once the import is
confirmed). What was running is started again after a successful import;
after a failed one the app stays stopped and the snapshot is named.

Not part of an import: the deploy .env and its keys. A tree exported from
an instance with CONTENT_VERSION_MODE=encrypted is unreadable unless this
instance's .env holds the key it was written with. Redis still holds
caches of the previous data: run ldcmd admin rebuild afterwards.
EOF
			;;
		"packs "|"packs restore")
			cat << 'EOF'
usage: ldcmd packs restore [--force]

Re-fetches every pack in the install registry (data/config) from the
store and verifies it, in a one-off app container (docker compose run
--no-deps): works while the app is crash-looping, e.g. after a lost
plugins volume. Then: ldcmd up.
  --force   re-download packs that look intact too
EOF
			;;
		"sidecar ")
			cat << 'EOF'
usage: ldcmd sidecar <sub-command> [args…]

Pack-owned services (a pack's deploy.json composeFiles) run as their own
compose projects next to the core stack.

  status                       installed sidecar packs and running projects
                               (default)
  configure [id…]              guided .env setup a pack declares
  up [--configure] [--force] [id…]
                               start (all, or the named) sidecars
  down [id…]                   stop them
  run <id> <command> [-- args…]
                               one-shot command from the pack's deploy.json
  upgrade <id> [args…]         = run <id> upgrade -- args…
  isolate web-render [options] guided web-render worker hardening

Run ldcmd sidecar <sub-command> --help for details.
EOF
			;;
		"sidecar status")
			cat << 'EOF'
usage: ldcmd sidecar status

Shows the sidecar plan the running app reports (packs:sidecars: installed
packs with composeFiles, their versions and env keys) and the sidecar
projects ldcmd started (sidecars/active.json in the deploy dir).
EOF
			;;
		"sidecar configure")
			cat << 'EOF'
usage: ldcmd sidecar configure [id…]

Runs the configure flow of the sidecar packs (all installed, or the named
ones): asks each env key the pack declares, with its texts, choices and
defaults, generates secrets and key pairs, checks the answers and writes
them to the deploy dir's .env. Existing values are never reset. Prints the
pack's operator notes at the end. Then: ldcmd up.
EOF
			;;
		"sidecar up")
			cat << 'EOF'
usage: ldcmd sidecar up [--configure] [--force] [id…]

Downloads (or bind-mounts from LIMEDOC_PLUGINS_DIR) the sidecar packs and
starts their compose projects; all installed sidecar packs, or the named
ones. Writes the reverse proxy snippets of packs that serve a subdomain.
  --configure   run ldcmd sidecar configure first
  --force       skip the preflight checks (missing env keys, ports)
EOF
			;;
		"sidecar down")
			cat << 'EOF'
usage: ldcmd sidecar down [id…]

Stops the sidecar projects ldcmd started (all, or the named ones). The
core stack keeps running.
EOF
			;;
		"sidecar run")
			cat << 'EOF'
usage: ldcmd sidecar run <id> <command> [-- args…]

Runs a one-shot command the pack declares in deploy.json `commands`
(docker compose run --rm, with the same env and network as sidecar up).
Arguments after -- go to the command; its exit code is passed through.
ldcmd sidecar status lists the installed packs; an unknown command name
lists the available ones.
EOF
			;;
		"sidecar upgrade")
			cat << 'EOF'
usage: ldcmd sidecar upgrade <id> [args…]

Same as ldcmd sidecar run <id> upgrade -- args…: for packs that update
their own runtime content (e.g. the ArtCraft apps) from a signed feed,
without a pack release. Idempotent.
EOF
			;;
		"sidecar isolate")
			cat << 'EOF'
usage: ldcmd sidecar isolate web-render [options]

Guided hardening of the web-render worker: persistent Redis ACL users
(app password and a restricted web-render user), its own render network,
optional Chromium egress settings and a sidecar key; restarts and
verifies. Asks before changing anything.
  -y, --yes                  apply without questions (required without a TTY)
  --verify                   only run the checks
  --rotate-worker-password   new password for the web-render Redis user
  --proxy-server URL         RENDER_PROXY_SERVER ("" clears; no commas)
  --resolver-rules RULES     RENDER_HOST_RESOLVER_RULES ("" clears; no commas)
  --network-name NAME        render network (default {basename}_render)
  --internal-network         create the render network without a route out
  --no-restart               write config only; restart later with ldcmd up
Env: LDCMD_ASSUME_YES=1 equals --yes.

What is enforced:
  Redis      the worker's user reaches render keys only (verified:
             NOPERM on app keys, password-less clients refused).
  Network    the worker sits on its own network with Redis and the app,
             away from the other containers. By default this is a plain
             bridge: it does NOT limit outbound connections (internet,
             LAN, host). --internal-network creates it without a route
             out; then external renders (pages fetched by URL) need a
             forward proxy attached to that network, or stop working. An
             existing render network is not converted (the command says
             how to remove it first).
  Egress     --proxy-server and --resolver-rules are Chromium settings
             inside the worker. They steer a working renderer; a
             compromised one need not honour them. Only an internal
             network (or a host firewall) is a boundary.
--verify reports whether the render network has a route out: a helper
container on it (LDCMD_HELPER_IMAGE) fetches LDCMD_EGRESS_PROBE_URL
(default http://example.com/); LDCMD_EGRESS_PROBE=0 skips that. A route
out is reported, not counted as a failed check.
EOF
			;;
		"redis "|"redis secure")
			cat << 'EOF'
usage: ldcmd redis secure [options]

Redis authentication: an ACL file in the Redis volume, an app password and
one restricted user per sidecar (web-render, vectorsearch); restarts and
verifies. Run by bootstrap and update.
  -y, --yes                   apply without questions (required without a TTY)
  --verify                    only run the checks
  --rotate-sidecar-passwords  new passwords for the sidecar Redis users
  --no-restart                write config only; restart later with ldcmd up
  --no-sidecars               do not recreate sidecars (the caller starts them)
Env: LDCMD_ASSUME_YES=1 equals --yes.
EOF
			;;
		"authz "|"authz grant-admin"|"authz revoke-admin")
			cat << 'EOF'
usage: ldcmd authz grant-admin <sub>
       ldcmd authz revoke-admin <sub>

Grant or revoke the in-app operator role (role:admin) for an IdP user id
(the OIDC `sub`), in the running app (authz/users/<sub>.json + Redis). The
first admin of an instance cannot use the admin UI before being admin; IdP
claims never grant this role. The user's next request picks it up.
EOF
			;;
		"acl "|"acl inherit-empty")
			cat << 'EOF'
usage: ldcmd acl inherit-empty [--path <tree prefix>] [--apply]

The permissions editor before app 0.27.0 stored every ACL key, untouched
ones as [], and [] replaces the folder's grants: a manager who gave one
person a right could lock everyone else out, themselves included. This
lists those ACL files and who gains read/edit/manage once the empty keys
inherit again. Review the list, then re-run with --apply.
EOF
			;;
		"admin ")
			cat << 'EOF'
usage: ldcmd admin <sub-command> [args…]

Maintenance in the running app (needs app 0.59.0 or later for rebuild,
check and blob-gc).

  rebuild [target]             rebuild caches and indexes from disk
                               (default all = Admin → Data cache rebuild)
  check tree [--repair-clashes [--apply]]
                               read-only tree consistency report
  blob-gc                      run one orphan blob sweep now
  heal-refs [--under <path>] [--apply]
                               repair broken embeds/links to files that
                               moved (app 0.67.0 or later)
  history fsck [-- args]       full version history check and repair
  history retention [-- args]  apply the history retention policy once

Run ldcmd admin <sub-command> --help for details.
EOF
			;;
		"admin rebuild")
			cat << 'EOF'
usage: ldcmd admin rebuild [all|tree|cid-index|policy-registry|public-asset-refs|manifests]

Rebuilds derived caches from the data on disk, in the running app's
container (same Redis and data). Running servers refresh their trees.
  all                 (default) everything Admin → Data cache rebuild does:
                      folder markers, user token caches, groups, asset
                      links, the cached tree with its policies and indexes,
                      spaces, retention archive index
  tree                the cached tree (entity graph, read policies, cid
                      index, browse tree) — fixes duplicated or "shadow"
                      folders and stale tree entries
  cid-index           content id → tree path index only
  policy-registry     read policy registry (re-stamps search rows)
  public-asset-refs   assets referenced by public documents
  manifests           location manifests and the pointer path index
EOF
			;;
		"admin check")
			cat << 'EOF'
usage: ldcmd admin check tree [--repair-clashes [--apply]]

Read-only report; exits 1 when it finds something:
  - folders that share a document's name (X next to X/ holding documents
    or subfolders). Such a folder borrows the document's permissions and
    moves and archives with it; new ones are refused since app 0.59.0.
  - the cached tree against the entity paths: entries listed under a
    folder they are not in (shadow folders), entries under several
    folders; fix with ldcmd admin rebuild tree
  - documents the content id index does not know at their path

  --repair-clashes   list the planned repair: each clashing folder is
                     renamed to X-folder (X-folder-2, …)
  --apply            schedule those renames as structured moves; the app
                     runs them after a 30 s veto window and heals links
EOF
			;;
		"admin blob-gc")
			cat << 'EOF'
usage: ldcmd admin blob-gc

Runs one orphan blob sweep now (as Admin → Run blob GC now). Unreferenced
blobs are deleted once the retention period ({CONFIG_DIR}/blob-gc.json or
BLOB_GC_RETENTION, default 30d) has passed since a sweep first found them
orphaned. Blobs that version history still names are kept.
EOF
			;;
		"admin heal-refs")
			cat << 'EOF'
usage: ldcmd admin heal-refs [--under <path>] [--apply]

Lists document references (embeds, images, links) whose target is gone and
the file with the same name that now holds it, if exactly one fits. Typical
after documents were moved without their files (before app 0.67.0 a moved
document kept relative paths that pointed into its new folder).
Candidates stay inside the document's claim space; documents outside
spaces never get a target inside one. Exits 1 while refs without a unique
target remain (fix those in the editor: References → Re-link).

  --under <path>   only documents below this tree path
  --apply          write the fixes (open editors receive them live)
EOF
			;;
		"admin history")
			cat << 'EOF'
usage: ldcmd admin history fsck [-- --no-sweep]
       ldcmd admin history retention [-- --apply [--bundles]]

  fsck        reconcile every object's version log with its history, heal
              journaled commits and sweep unreferenced chunks older than
              the grace window. Safe next to the app; prefer a quiet
              moment on busy instances.
  retention   apply the history retention policy
              ({CONFIG_DIR}/history-retention.json) once. A dry run unless
              --apply; --bundles also drops bundle records whose versions
              are all gone.
Arguments after -- go to the app task (deno task history:<fsck|retention>).
EOF
			;;
		"plugin "|"skin "|"template ")
			_ht_k="${_ht_cmd}"
			cat << EOF
usage: ldcmd ${_ht_k} <sub-command> [args…]

Packs in the running app (instance deploy dir, or pack-dev compose.dev.yml
in a pack checkout).

  ls [--installed]              store listing with ✓ marks (or installed only)
  install [--force] [--with-deps] <id>
                                install a ${_ht_k} pack from the store
  uninstall [--force] <id>      remove an installed ${_ht_k} pack
  update [--check] [--no-restart] [<id>…]
                                update to the newest verified store versions
EOF
			case "${_ht_k}" in
				plugin|template)
					cat << EOF
  activate <id>                 switch an installed ${_ht_k} on
  deactivate <id>               switch it off (stays installed)
EOF
					;;
				skin)
					cat << 'EOF'
  select <fullSkinId>           make an installed full skin active
  palette <id>|none             choose the palette pack (none = skin's own)
EOF
					;;
			esac
			cat << EOF

Run ldcmd ${_ht_k} <sub-command> --help for details.
EOF
			;;
		"plugin ls"|"skin ls"|"template ls")
			cat << EOF
usage: ldcmd ${_ht_cmd} ls [--installed]

Lists the ${_ht_cmd} packs in the store (newest verified version of each
vetted publisher's packs), with ✓ for the
installed ones and their versions. --installed lists only installed packs
(also those not in the store).
EOF
			;;
		"plugin install"|"skin install"|"template install")
			cat << EOF
usage: ldcmd ${_ht_cmd} install [--force] [--with-deps] <id>

Downloads the ${_ht_cmd} pack from the store, verifies its signature and
hash, installs it and reloads the running app.
  --force       reinstall an installed pack
  --with-deps   also install the packs it requires
A plugin with a sidecar prints the next steps (ldcmd sidecar up <id>
--configure, then ldcmd up).
EOF
			;;
		"plugin uninstall"|"skin uninstall"|"template uninstall")
			cat << EOF
usage: ldcmd ${_ht_cmd} uninstall [--force] <id>

Removes an installed ${_ht_cmd} pack and reloads the running app. Refuses
when installed packs require it, unless --force (removes them too). In a
deploy dir a plugin's sidecar is stopped. A pack that is not installed is
a no-op.
EOF
			;;
		"plugin update"|"skin update"|"template update")
			cat << EOF
usage: ldcmd ${_ht_cmd} update [--check] [--no-restart] [<id>…]

Updates installed ${_ht_cmd} packs (all, or the named ones) to the newest
verified store versions; never downgrades.
  --check, --dry-run   only list available updates
  --no-restart         do not restart sidecars / the app; print the steps
In a deploy dir updated sidecars are restarted, and the app when
templates changed.
EOF
			;;
		"plugin activate"|"plugin deactivate"|"template activate"|"template deactivate")
			cat << EOF
usage: ldcmd ${_ht_cmd} activate <id>
       ldcmd ${_ht_cmd} deactivate <id>

Switches an installed ${_ht_cmd} on or off (operator setting in
data/config/<id>.json); it stays installed. Deactivating a plugin also
switches off plugins that require it. Open browser tabs need a reload.
EOF
			;;
		"skin select"|"skin palette")
			cat << 'EOF'
usage: ldcmd skin select <fullSkinId>
       ldcmd skin palette <palettePackId>|none

select    make an installed full skin the active core skin (SKIN_CORE)
palette   choose the palette pack; none uses the skin's own palette
EOF
			;;
		"init ")
			cat << 'EOF'
usage: ldcmd init

Pack checkout: detects the pack (kind, id, directory) or asks for it and
writes .env.ldcmd. Other pack-dev commands do this on first use.
EOF
			;;
		"setup ")
			cat << 'EOF'
usage: ldcmd setup

Pack checkout: pulls the limedoc-dev image and creates .env from
.env.example when missing. No app git clone needed.
EOF
			;;
		"logs ")
			cat << 'EOF'
usage: ldcmd logs [service] [docker compose logs args…]

Pack checkout: follows the logs of the app (or the named service).
EOF
			;;
		"sh ")
			cat << 'EOF'
usage: ldcmd sh [service] [args…]

Pack checkout: opens a shell in the app container (or the named service).
EOF
			;;
		"test ")
			cat << 'EOF'
usage: ldcmd test [deno test args…]

Pack checkout: runs the pack's tests (deno test -A) inside the running
limedoc-dev app container. Start it first: ldcmd up.
EOF
			;;
		"fmt "|"lint "|"check ")
			cat << EOF
usage: ldcmd ${_ht_cmd}

Pack checkout: runs deno ${_ht_cmd} on the pack inside the running
limedoc-dev app container$( [ "${_ht_cmd}" = check ] && printf '%s' \
	" (plugins: also the import boundary check)").
EOF
			;;
		"pack ")
			cat << 'EOF'
usage: ldcmd pack [args…]

Pack checkout: builds the pack zip and .sha256 inside the app container
(frozen lockfiles) and copies them into the current directory.
EOF
			;;
		"publish ")
			cat << 'EOF'
usage: ldcmd publish [--replace]

Pack checkout: builds the pack and uploads zip + .sha256 to the package
registry. A version that is already published is refused (published
versions are immutable: bump the version); --replace deletes and uploads
it again. Reads PACKAGE_TOKEN (and optionally PACKAGE_OWNER,
PACKAGE_REGISTRY_URL) from .publish.env; the token needs read and write
on packages.
EOF
			;;
		"version ")
			echo "usage: ldcmd version     (also --version, -V)"
			;;
		"help ")
			echo "usage: ldcmd help [<command> [<sub-command>]]"
			;;
		*)
			return 1
			;;
	esac
}

# show_help <command> [<sub>] — the sub-command's help, else the
# command's; dies when neither exists.
show_help() {
	help_text "$@" 2>/dev/null && return 0
	help_text "${1:-}" && return 0
	die "no help for '${1:-}' (try: ldcmd help)"
}

# help_requested args… — true when -h / --help / help appears as an
# argument before `--` (arguments after it belong to someone else).
help_requested() {
	for _hr_a in "$@"; do
		case "${_hr_a}" in
			--) return 1 ;;
			-h|--help) return 0 ;;
		esac
	done
	[ "${1:-}" = "help" ]
}

# first_sub_command args… — first argument that is not an option.
first_sub_command() {
	for _fs_a in "$@"; do
		case "${_fs_a}" in
			--) return 0 ;;
			-*|help) ;;
			*) printf '%s\n' "${_fs_a}"; return 0 ;;
		esac
	done
}

# ── admin ─────────────────────────────────────────────────────────────────────

ADMIN_REBUILD_TARGETS="all tree cid-index policy-registry public-asset-refs manifests"

# admin_task_exec <deno task> [args…] — in the running app container; the
# task's exit code is passed through.
admin_task_exec() {
	_at_task="$1"
	shift
	resolve_prod_deploy_dir
	prod_core_compose_args
	command -v docker >/dev/null 2>&1 || die "docker is required"
	isolate_compose ps -q app 2>/dev/null | grep -q . ||
		die "app is not running in ${DEPLOY_DIR} (start it with: ldcmd up)"
	case "${_at_task}" in
		admin:*)
			isolate_compose exec -T app sh -c \
				'grep -q "\"$1\"" deno.json' _ "${_at_task}" 2>/dev/null ||
				die "this app has no ${_at_task} task (needs limedoc 0.59.0 or later; ldcmd update)"
			;;
	esac
	_at_st=0
	isolate_compose exec -T app deno task -q "${_at_task}" -- "$@" ||
		_at_st=$?
	return "${_at_st}"
}

cmd_admin() {
	_ad_sub="${1:-}"
	[ "$#" -gt 0 ] && shift
	case "${_ad_sub}" in
		rebuild)
			[ "$#" -le 1 ] || {
				help_text admin rebuild >&2
				die "admin rebuild: takes one target"
			}
			_ad_target="${1:-all}"
			case " ${ADMIN_REBUILD_TARGETS} " in
				*" ${_ad_target} "*) ;;
				*)
					help_text admin rebuild >&2
					die "admin rebuild: unknown target '${_ad_target}'"
					;;
			esac
			admin_task_exec admin:rebuild "${_ad_target}"
			;;
		check)
			[ "${1:-}" = "tree" ] || {
				help_text admin check >&2
				die "admin check: expected 'tree'"
			}
			shift
			_ad_repair=""
			_ad_apply=""
			while [ "$#" -gt 0 ]; do
				case "$1" in
					--repair-clashes) _ad_repair="--repair-clashes" ;;
					--apply) _ad_apply="--apply" ;;
					*)
						help_text admin check >&2
						die "admin check tree: unknown argument '$1'"
						;;
				esac
				shift
			done
			[ -z "${_ad_apply}" ] || [ -n "${_ad_repair}" ] ||
				die "admin check tree: --apply needs --repair-clashes"
			# shellcheck disable=SC2086
			admin_task_exec admin:check-tree ${_ad_repair} ${_ad_apply}
			;;
		blob-gc)
			[ "$#" -eq 0 ] || die "admin blob-gc: takes no arguments"
			admin_task_exec admin:blob-gc
			;;
		heal-refs)
			_ad_under=""
			_ad_apply=""
			while [ "$#" -gt 0 ]; do
				case "$1" in
					--under)
						[ "$#" -ge 2 ] || die "admin heal-refs: --under needs a path"
						_ad_under="$2"
						shift
						;;
					--apply) _ad_apply="--apply" ;;
					*)
						help_text admin heal-refs >&2
						die "admin heal-refs: unknown argument '$1'"
						;;
				esac
				shift
			done
			if [ -n "${_ad_under}" ]; then
				# shellcheck disable=SC2086
				admin_task_exec admin:heal-refs --under "${_ad_under}" ${_ad_apply}
			else
				# shellcheck disable=SC2086
				admin_task_exec admin:heal-refs ${_ad_apply}
			fi
			;;
		history)
			_ad_h="${1:-}"
			[ "$#" -gt 0 ] && shift
			case "${_ad_h}" in
				fsck|retention) ;;
				*)
					help_text admin history >&2
					die "admin history: expected fsck or retention"
					;;
			esac
			[ "${1:-}" != "--" ] || shift
			admin_task_exec "history:${_ad_h}" "$@"
			;;
		*)
			help_text admin >&2
			die "admin: unknown sub-command '${_ad_sub}' (rebuild|check|blob-gc|heal-refs|history)"
			;;
	esac
}

# ── commands that skip pack resolve ───────────────────────────────────────────

# Test hook: `LDCMD_SOURCE_ONLY=1 . ldcmd` loads functions without dispatching.
if [ "${LDCMD_SOURCE_ONLY:-}" = "1" ]; then
	# shellcheck disable=SC2317
	return 0 2>/dev/null || exit 0
fi

# Global: -i/--instance <id|path> works on that instance for this command.
while [ $# -gt 0 ]; do
	case "$1" in
		-i|--instance)
			[ $# -ge 2 ] || die "$1 needs an instance id or path (ldcmd list)"
			LIMEDOC_DEPLOY_DIR="$(resolve_instance_ref "$2")"
			LDCMD_INSTANCE_SOURCE="ldcmd $1"
			export LIMEDOC_DEPLOY_DIR LDCMD_INSTANCE_SOURCE
			shift 2
			;;
		*) break ;;
	esac
done

cmd="${1:-help}"
shift || true

case "${cmd}" in
	version|--version|-V)
		echo "ldcmd ${LDCMD_VERSION}"
		exit 0
		;;
	help|--help|-h)
		if [ "$#" -gt 0 ]; then
			show_help "$@"
			exit 0
		fi
		cat << EOF
ldcmd ${LDCMD_VERSION} — Limedoc pack + operator bridge

Usage: ldcmd [-i <instance>] <command> [args…]

Instances (several per host; run ldcmd from anywhere):
  list              Instances on this host (running or not); * = selected
  use <id|path>     Select the instance all operator commands work on
  use               Show the selection; use --clear forgets it
  -i <id|path>      Work on that instance for this one command
                    Without a selection: the current deploy dir, else the
                    only instance on the host. LIMEDOC_DEPLOY_DIR also works.

Operators (no app git clone):
  bootstrap         Fetch limedoc-deploy zip, wizard, compose pull/up
                    (prompt: deploy dir name under cwd, default limedoc;
                     or LIMEDOC_DEPLOY_DIR=/abs/path)
  install           Alias for bootstrap
  update [--check] [--version X.Y.Z|latest|edge] [--image REPO]
         [--with-packs] [--yes]
                    Update the instance: signed deploy bundle, app image
                    (LIMEDOC_IMAGE tag, or --version; --image switches the
                    repository), sidecars. Checks the image exists first;
                    backs up replaced files under .ldcmd-backup/.
                    --with-packs also updates installed packs. --check only
                    reports.
  self-update [--check] [--version X.Y.Z] [--force]
                    Replace ldcmd with the latest signed release.
  up / down / status
                    Prod deploy dir: core (redis+app) + pack sidecars
                    Pack-dev cwd: compose.dev.yml (+ pack composeFiles)
  data export [DIR] Dump limedoc_data + vectorsearch cache into one host tree
  data import [--yes] [--no-backup] [DIR]
                    Replace the two named volumes with that tree (asks
                    first, snapshots the current data volume)
  packs restore [--force]
                    Re-fetch packs from install registry (compose run --no-deps;
                    works when app is crash-looping). Then: ldcmd up
  sidecar status | sidecar configure [id…] | sidecar up [id…] | sidecar down [id…]
                    Host-start pack-owned compose (download zip or
                    LIMEDOC_PLUGINS_DIR bind-mount). up supports
                    --configure (wizard first) and --force (skip preflight)
  sidecar run <id> <command> [-- args…]
                    One-shot command a pack declares in deploy.json
                    \`commands\` (docker compose run --rm, same env and
                    network as up); exit code passed through.
  sidecar upgrade <id> [args…]
                    = sidecar run <id> upgrade -- args… (packs that update
                    their own runtime content, e.g. app builds)
  authz grant-admin <sub> | authz revoke-admin <sub>
                    In-app operator role (role:admin) for an IdP user id, in
                    the running app; the way to create the first admin.
  acl inherit-empty [--path <prefix>] [--apply]
                    List (then repair) ACL files of the old permissions
                    editor whose empty keys lock folder grants out.
  admin rebuild [all|tree|cid-index|policy-registry|public-asset-refs|manifests]
                    Rebuild caches / the cached tree from disk in the app
                    (all = Admin → Data cache rebuild; tree fixes shadow
                    or duplicated folders).
  admin check tree [--repair-clashes [--apply]]
                    Tree consistency report; repairs folders that share a
                    document's name.
  admin heal-refs [--under <path>] [--apply]
                    Repair broken embeds/links to files that moved.
  admin blob-gc | admin history fsck|retention [-- args]
                    Orphan blob sweep; version history check / retention.
  redis secure [--yes] [--verify] [--rotate-sidecar-passwords] [--no-restart]
                    Redis auth: ACL file in the Redis volume, app password,
                    one restricted user per sidecar (web-render, vectorsearch);
                    restarts + verifies. Run by bootstrap and update.
  sidecar isolate web-render [--yes] [--verify] [--rotate-worker-password]
                    [--proxy-server URL] [--resolver-rules RULES] [--no-restart]
                    [--internal-network]
                    Guided worker hardening: persistent Redis ACL users (app
                    password + restricted web-render user), own render
                    network (without a route out: --internal-network),
                    Chromium egress settings, sidecar key; restarts + verifies.
                    Asks before changing anything; --yes for automation.
  plugin|skin|template install [--force] [--with-deps] <id>
  plugin|skin|template uninstall [--force] <id>
  plugin|skin|template update [--check] [--no-restart] [<id>…]
                    Update installed packs (all of the kind, or the named
                    ones) to the newest verified store versions; never downgrades.
                    Prod: restarts updated sidecars, restarts the app when
                    templates changed (--no-restart: only print the steps).
  plugin|skin|template ls [--installed]
  plugin|template activate|deactivate <id>
  skin select <fullSkinId> | skin palette <id>|none
                    Install / list / uninstall packs in a running app
                    (prod deploy dir or pack-dev compose.dev.yml).
                    Default ls = store listing with ✓ installed marks.
                    Uninstall refuses dependents unless --force (cascade).
                    Plugin uninstall runs sidecar down in prod only when
                    the pack declares a sidecar (deploy.json composeFiles).
                    Skins: select active full-skin + optional palette.

Pack developers (no app git clone; reach-in to limedoc-dev):
  init              Detect/prompt pack config → write .env.ldcmd
  setup up down logs sh test fmt lint check pack publish
  version           Print ldcmd version

Details: ldcmd <command> --help, ldcmd <command> <sub-command> --help
         (or ldcmd help <command> [<sub-command>])

Install: https://git.belowtoxic.cloud/limedoc/ldcmd
Package: https://git.belowtoxic.cloud/api/packages/limedoc/generic/ldcmd/
Deploy bundle: …/generic/limedoc/…/limedoc-deploy-*.zip

EOF
		exit 0
		;;
esac

# `ldcmd <command> [<sub>] --help`: before any instance / pack resolution.
# A command group without a sub-command: its help on stderr, usage error.
case "${cmd}" in
	admin|data|packs|redis|authz|acl|plugin|skin|template)
		if [ "$#" -eq 0 ]; then
			help_text "${cmd}" >&2
			exit 2
		fi
		;;
esac
if help_requested "$@"; then
	show_help "${cmd}" "$(first_sub_command "$@")"
	exit 0
fi

# Operator bootstrap (no pack cwd)
case "${cmd}" in
	admin)
		cmd_admin "$@"
		exit $?
		;;
	bootstrap|install)
		cmd_bootstrap "$@"
		exit $?
		;;
	update)
		cmd_update "$@"
		exit $?
		;;
	list|ls)
		cmd_list "$@"
		exit $?
		;;
	use)
		cmd_use "$@"
		exit $?
		;;
	self-update)
		cmd_self_update "$@"
		exit $?
		;;
	authz)
		cmd_authz "$@"
		exit $?
		;;
	acl)
		cmd_acl "$@"
		exit $?
		;;
	redis)
		sub="${1:-}"
		shift || true
		case "${sub}" in
			secure) cmd_redis_secure "$@" ;;
			*) help_text redis >&2; die "redis: unknown sub-command '${sub}' (secure)" ;;
		esac
		exit $?
		;;
	sidecar)
		sub="${1:-status}"
		shift || true
		case "${sub}" in
			status) cmd_sidecar_status ;;
			configure) cmd_sidecar_configure "$@" ;;
			up) cmd_sidecar_up "$@" ;;
			down) cmd_sidecar_down "$@" ;;
			run) cmd_sidecar_run "$@" ;;
			upgrade) cmd_sidecar_upgrade "$@" ;;
			isolate) cmd_sidecar_isolate "$@" ;;
			*) help_text sidecar >&2; die "sidecar: unknown sub-command '${sub}' (status|configure|up|down|run|upgrade|isolate)" ;;
		esac
		exit $?
		;;
	data)
		sub="${1:-}"
		if [ "$#" -gt 0 ]; then
			shift
		fi
		case "${sub}" in
			export) cmd_data_export "$@" ;;
			import) cmd_data_import "$@" ;;
			*) help_text data >&2; die "data: unknown sub-command '${sub:-}' (export|import)" ;;
		esac
		exit $?
		;;
	packs)
		sub="${1:-}"
		if [ "$#" -gt 0 ]; then
			shift
		fi
		case "${sub}" in
			restore) cmd_packs_restore "$@" ;;
			*) help_text packs >&2; die "packs: unknown sub-command '${sub:-}' (restore)" ;;
		esac
		exit $?
		;;
	plugin|skin|template)
		cmd_pack_kind_ops "${cmd}" "$@"
		exit $?
		;;
	up)
		if prod_context; then
			cmd_prod_up "$@"
			exit $?
		fi
		;;
	down)
		if prod_context; then
			cmd_prod_down "$@"
			exit $?
		fi
		;;
	status)
		if prod_context; then
			cmd_prod_status
			exit $?
		fi
		die "status: works on an instance (run outside the pack checkout, or ldcmd -i <id> status)"
		;;
esac

# Pack-context commands. Anything else is unknown: reject it here, before
# pack resolve prompts for a pack config in an operator's directory.
case "${cmd}" in
	init|setup|up|down|logs|sh|test|fmt|lint|check|pack|publish) ;;
	*) die "unknown command '${cmd}' (ldcmd ${LDCMD_VERSION}; try: ldcmd help, or ldcmd self-update for newer commands)" ;;
esac
resolve_config "$([ "${cmd}" = "init" ] && echo init || true)"
setup_compose

case "${cmd}" in
	init)
		info "ready: ${PACK_KIND}:${PACK_ID} (${PACK_DIR})"
		;;
	setup)
		info "pulling limedoc-dev (no app git clone; tasks reach into ${APP_SERVICE})"
		${COMPOSE_CMD} pull "${APP_SERVICE}" || true
		if [ ! -f ".env" ] && [ -f ".env.example" ]; then
			cp .env.example .env
		fi
		;;
	up)
		${COMPOSE_CMD} up --build -d "$@"
		pack_dev_sidecar_up
		;;
	down)
		pack_dev_sidecar_down
		${COMPOSE_CMD} down "$@"
		;;
	logs)
		service="${1:-${APP_SERVICE}}"
		shift || true
		${COMPOSE_CMD} logs -f "${service}" "$@"
		;;
	sh)
		service="${1:-${APP_SERVICE}}"
		shift || true
		${COMPOSE_CMD} exec "${service}" sh "$@"
		;;
	test)
		require_up
		exec_in_app deno test --no-check -A "${PACK_DIR}" "$@"
		;;
	fmt)
		require_up
		exec_in_app deno fmt "${PACK_DIR}"
		;;
	lint)
		require_up
		exec_in_app deno lint "${PACK_DIR}"
		;;
	check)
		require_up
		if [ "${PACK_KIND}" = "plugin" ]; then
			exec_in_app sh -c "
				deno check '${PACK_DIR}/${PACK_ID}.ts' && \
				deno run -A /limedoc/scripts/check-plugin-boundaries.ts 2>&1
			"
		else
			exec_in_app deno check "${PACK_DIR}/limedoc.project.json" 2>/dev/null ||
				true
		fi
		;;
	pack)
		require_up
		exec_in_app deno task ${PACK_TASK} -- "${PACK_DIR}" --out /tmp/dist "$@"
		${COMPOSE_CMD} exec "${APP_SERVICE}" sh -c \
			"ls /tmp/dist/${PACK_ID}-*.zip /tmp/dist/${PACK_ID}-*.sha256 2>/dev/null" |
			while read -r f; do
				${COMPOSE_CMD} cp "${APP_SERVICE}:${f}" ./ 2>/dev/null || true
			done
		;;
	publish)
		_pub_replace=0
		for _pub_arg in "$@"; do
			case "${_pub_arg}" in
				--replace) _pub_replace=1 ;;
				*) die "publish: unknown argument '${_pub_arg}' (--replace)" ;;
			esac
		done
		_publish_env=""
		if [ -f ".publish.env" ]; then
			_publish_env=".publish.env"
		elif [ -f ".forgejo.env" ]; then
			_publish_env=".forgejo.env"
			info "using legacy .forgejo.env (prefer .publish.env)"
		else
			die ".publish.env not found (legacy .forgejo.env also accepted)"
		fi
		# shellcheck disable=SC1091
		set -a
		. "./${_publish_env}"
		set +a
		PACKAGE_TOKEN="${PACKAGE_TOKEN:-${FORGEJO_TOKEN:-}}"
		PACKAGE_OWNER="${PACKAGE_OWNER:-${FORGEJO_OWNER:-}}"
		PACKAGE_REGISTRY_URL="${PACKAGE_REGISTRY_URL:-${FORGEJO_BASE_URL:-}}"
		[ -n "${PACKAGE_TOKEN}" ] || die "PACKAGE_TOKEN not set in ${_publish_env}"
		require_up
		exec_in_app deno task ${PACK_TASK} -- "${PACK_DIR}" --out /tmp/dist
		VERSION="$(json_field limedoc.project.json version || true)"
		[ -n "${VERSION}" ] ||
			die "could not read version from limedoc.project.json"
		ZIP="${PACK_ID}-${VERSION}.zip"
		SHA="${PACK_ID}-${VERSION}.sha256"
		${COMPOSE_CMD} cp "${APP_SERVICE}:/tmp/dist/${ZIP}" ./ 2>/dev/null || true
		${COMPOSE_CMD} cp "${APP_SERVICE}:/tmp/dist/${SHA}" ./ 2>/dev/null || true
		OWNER="${PACKAGE_OWNER:-${PACKAGE_OWNER_DEFAULT}}"
		BASE_URL="${PACKAGE_REGISTRY_URL:-${DEFAULT_PACKAGE_REGISTRY_URL}}"
		PKG_BASE="${BASE_URL}/api/packages/${OWNER}/generic/${PACK_ID}/${VERSION}"
		[ -f "${ZIP}" ] && [ -f "${SHA}" ] ||
			die "publish: ${ZIP} and ${SHA} were not produced"
		# The token reaches curl in a header file, never on a command line
		# (every user of the host can read those).
		_pub_hdr="$(umask 077 && mktemp)" || die "mktemp failed"
		# shellcheck disable=SC2064
		trap "rm -f '${_pub_hdr}'" EXIT
		printf 'Authorization: token %s\n' "${PACKAGE_TOKEN}" > "${_pub_hdr}"
		# A published version is what its installers verified: it is only
		# replaced on request.
		_pub_http="$(ld_curl "${LDCMD_META_MAX_BYTES}" -sS -o /dev/null \
			-w '%{http_code}' -H "@${_pub_hdr}" \
			"${BASE_URL}/api/v1/packages/${OWNER}/generic/${PACK_ID}/${VERSION}")" ||
			die "publish: cannot ask ${BASE_URL} whether ${PACK_ID} ${VERSION} is published"
		case "${_pub_http}" in
			404) ;;
			200)
				[ "${_pub_replace}" = "1" ] ||
					die "publish: ${PACK_ID} ${VERSION} is already published. Bump the version in limedoc.project.json; to overwrite the published files anyway: ldcmd publish --replace"
				DEL_HTTP="$(ld_curl "${LDCMD_META_MAX_BYTES}" -sS -o /dev/null \
					-w '%{http_code}' -X DELETE -H "@${_pub_hdr}" "${PKG_BASE}")"
				case "${DEL_HTTP}" in
					204|404) echo "ldcmd: --replace: removed the published ${PACK_ID} ${VERSION} (HTTP ${DEL_HTTP})" ;;
					*) die "DELETE ${PKG_BASE} failed: HTTP ${DEL_HTTP}" ;;
				esac
				;;
			*) die "publish: cannot tell whether ${PACK_ID} ${VERSION} is published (HTTP ${_pub_http} from ${BASE_URL}; the token needs read:package)" ;;
		esac
		ld_curl "${LDCMD_META_MAX_BYTES}" -sSf -H "@${_pub_hdr}" \
			--upload-file "${ZIP}" \
			"${PKG_BASE}/${ZIP}"
		ld_curl "${LDCMD_META_MAX_BYTES}" -sSf -H "@${_pub_hdr}" \
			--upload-file "${SHA}" \
			"${PKG_BASE}/${SHA}"
		rm -f "${_pub_hdr}"
		trap - EXIT
		echo "ldcmd: published ${PACK_ID} ${VERSION}"
		;;
	*)
		die "unknown command '${cmd}' (try: ldcmd help)"
		;;
esac
