#!/usr/bin/env bash
# opensim setup: the engine gives the screens (it is the scenario), this draws the one it gets, sends it back filled with the button that
# was pressed, and does the action it answers: another screen, the same one with what is wrong, quit with a message, abort with an error.

USAGE='opensim setup [-hqv] [--config FILE] [--prepare FILE] [--apply FILE] [--region-config FILE] [--existing] [--oar FILE | --dump FILE] [--show-passwords] [--legacy [--unattended | --config-keys]]'
HELP="Shows the setup questions and applies the confirmed settings.
  --config FILE   prefill answers from a JSON configuration
  --prepare FILE  save answers privately without creating the installation
  --apply FILE    apply a prepared configuration without further questions
  --region-config FILE  adopt an existing Region.ini in a simulator setup
  --legacy        beside a pre-existing install (/opt/opensim): with --unattended or --config-keys, its scenario without screens
  --unattended    with --legacy, nobody there: the answers of --config, a default for each one missing, no screen; exit 0 done,
                  1 a step failed, 2 an answer refused (nothing done); 4 is a stop asked at a screen
  --config-keys   with --legacy, the answers --config takes for it: name, values, default, what it is
  --show-passwords  show the passwords of the database accounts in the review (masked by default; Show passwords there too)
  --existing      take over the region the grid has of the name given (restored, or moved from another server): its UUID,
                  place, size and owner kept; refused while the simulator that runs it elsewhere answers
  --oar FILE      load this archive of the region (OAR) into the first region once it runs
  --dump FILE     make the database of the simulator from this dump of the database of the one the region comes from (.sql or
                  .sql.gz, of opensim backup or mysqldump), before it starts"

source "$(dirname "$(realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")/../src/lib/common"
source "$CLI_ROOT/src/lib/ui"
# Its client run by root (setup_client): the engine as the system user, whose files it writes
if [[ -n "${OPENSIM_SETUP_ENGINE_AS:-}" && $(id -u) -eq 0 ]]; then
	engine() { system_user=$OPENSIM_SETUP_ENGINE_AS as_system_user "$OPENSIM_API" "$@"; }
fi

setup_config=${OPENSIM_SETUP_CONFIG_FILE:-}
setup_config_explicit=no
prepare_file=
apply_file=
region_config=
region_content='{}'
setup_mode=apply
while (($#)); do
	case "$1" in
		--config)
			(($# > 1)) || die "opensim setup --config requires a JSON file"
			setup_config=$2
			setup_config_explicit=yes
			shift 2
			;;
		--config=*) setup_config_explicit=yes; setup_config=${1#*=}; [[ -n "$setup_config" ]] || die "opensim setup --config requires a JSON file"; shift ;;
		--region-config)
			(($# > 1)) && [[ "$2" != -* ]] || die "opensim setup --region-config requires an INI file"
			region_config=$2
			shift 2
			;;
		--region-config=*) region_config=${1#*=}; [[ -n "$region_config" ]] || die "opensim setup --region-config requires an INI file"; shift ;;
		--existing) region_content=$(jq -c '. + {existing: "yes"}' <<<"$region_content"); shift ;;
		--show-passwords) region_content=$(jq -c '. + {show_passwords: true}' <<<"$region_content"); shift ;;
		# An install of before the kit on this machine: its scenario first (run as root: its steps of root are this command's)
		--legacy) setup_legacy=yes; shift ;;
		--unattended) setup_unattended=yes; shift ;;
		--config-keys) setup_keys=yes; shift ;;
		--oar | --dump)
			(($# > 1)) && [[ "$2" != -* ]] || die "opensim setup $1 requires a file"
			[[ -r "$2" ]] || die "cannot read $2"
			region_content=$(jq -c --arg key "${1#--}" --arg file "$(realpath "$2")" '. + {($key): $file}' <<<"$region_content")
			shift 2
			;;
		--oar=* | --dump=*)
			[[ -r "${1#*=}" ]] || die "cannot read ${1#*=}"
			key=${1%%=*}
			region_content=$(jq -c --arg key "${key#--}" --arg file "$(realpath "${1#*=}")" '. + {($key): $file}' <<<"$region_content")
			shift
			;;
		--apply)
			(($# > 1)) && [[ "$2" != --* ]] || die "opensim setup --apply requires a JSON file"
			apply_file=$2
			shift 2
			;;
		--apply=*) apply_file=${1#*=}; [[ -n "$apply_file" ]] || die "opensim setup --apply requires a JSON file"; shift ;;
		--prepare)
			(($# > 1)) && [[ "$2" != -* ]] || die "opensim setup --prepare requires a JSON file"
			prepare_file=$2
			setup_mode=prepare
			shift 2
			;;
		--prepare=*) prepare_file=${1#*=}; [[ -n "$prepare_file" ]] || die "opensim setup --prepare requires a JSON file"; setup_mode=prepare; shift ;;
		*) shift ;;
	esac
done
apply_request=
if [[ -n "$apply_file" ]]; then
	[[ "$setup_config_explicit" == yes ]] || setup_config=
	[[ -z "$prepare_file" && -z "$setup_config" && -z "$region_config" ]] || die "--apply cannot be combined with --prepare, --config or --region-config"
	apply_filter='
		if (.answers.admin_user // "") == "" then
			.answers.admin_user = $admin_user |
			.answers.admin_password = $admin_password
		elif (.answers.admin_password // "") == "" and .answers.admin_user == $admin_user then
			.answers.admin_password = $admin_password
		else . end |
		{data: {type: "steps", attributes: {mode: "apply", configuration: .}}}
	'
	if [[ "$apply_file" == - ]]; then
		apply_input=$(cat) || die "cannot read prepared setup from standard input"
	else
		[[ -r "$apply_file" ]] || die "cannot read prepared setup: $apply_file"
		apply_input=$(<"$apply_file")
	fi
fi
setup_prefill='{}'
setup_prefill_type=
setup_occupied_ports=
if [[ -n "$setup_config" ]]; then
	[[ -r "$setup_config" ]] || die "cannot read setup config: $setup_config"
	setup_prefill=$(jq -ce 'if (.answers | type) == "object" then .answers elif type == "object" then . else error("expected object") end' "$setup_config") || die "setup config must be a JSON object"
	if jq -e 'has("occupied_ports")' "$setup_config" >/dev/null; then
		setup_occupied_ports=$(jq -ce '.occupied_ports | select(type == "array" and all(.[]; type == "number" and floor == . and . >= 1 and . <= 65535))' "$setup_config") || die "setup config occupied_ports must be a list of valid ports"
	fi
	setup_prefill_type=$(jq -r '.type // empty' <<<"$setup_prefill")
fi

if [[ -n "$region_config" ]]; then
	[[ -r "$region_config" ]] || die "cannot read region configuration: $region_config"
	setup_prefill=$(jq -c --rawfile region "$region_config" '. + {existing_region:$region}' <<<"$setup_prefill") || die "cannot read region configuration"
fi
setup_prefill=$(jq -c --argjson content "$region_content" '. + $content' <<<"$setup_prefill")
setup_prefill=$(jq -c 'if (.existing_region // "") != "" then .type //= "simulator" else . end' <<<"$setup_prefill")
setup_prefill_type=$(jq -r '.type // empty' <<<"$setup_prefill")

state= button=next answers='{}'
errors=$(mktemp) answer=$(mktemp) prepared_tmp=
trap 'rm -f "$errors" "$answer"; [[ -z "$prepared_tmp" ]] || rm -f "$prepared_tmp"' EXIT

# How a value of the configuration is given to a field: a boolean as yes or no, a field of yes and no told yes or no whatever word
PREFILL_YN='def yn: if type == "boolean" then (if . then "yes" else "no" end) else tostring end;
def yesno($o): if ($o | type) == "object" and ($o | has("yes")) and ($o | has("no")) then (ascii_downcase | if IN("true", "1", "on", "y") then "yes" elif IN("false", "0", "off", "n") then "no" else . end) else . end;
'

# Show what the engine told since the last time. A line starting with "~" is what a wait is on: on a terminal it takes one line
# that the next one replaces, elsewhere it is not shown.
pending=
show_progress() {
	local size line
	size=$(wc -c <"$errors")
	if ((size > shown)); then
		while IFS= read -r line; do
			[[ $line == "opensim: "* ]] || continue
			# What the engine says while it works is the live line, but its errors and warnings, kept as lines
			line=${line#opensim: }
			line=${line#"${line%%[![:space:]]*}"}
			if [[ $line == "~"* || ! ${line,,} =~ (error|warn|fail|cannot|could not) ]]; then
				line=${line#\~}
				# The mark of a wait the engine gives an item of its step too ([3/4] Start: ~AssetServiceConnector 1/27)
				line=${line/: \~/: }
				# A step of a run the engine names (Backup: database x), numbered by the labels of the run it gave (STEP_LABELS)
				if [[ -n "${STEP_LABELS:-}" && $line != "["* ]] && grep -qxF -- "${line%%:*}" <<<"$STEP_LABELS"; then
					line="[$(grep -nxF -- "${line%%:*}" <<<"$STEP_LABELS" | cut -d: -f1)/$(grep -c . <<<"$STEP_LABELS")] $line"
				fi
				# The step it is in, kept while its items go by: [2/3] Start: kimbe_test.welcome ready (1/1)
				[[ $line == "["[0-9]*"/"[0-9]*"] "* ]] && stage=${line%%:*}
				[[ $line == "["[0-9]*"/"[0-9]*"] "* || -z ${stage:-} ]] || line="$stage: $line"
				started=${started:-$SECONDS}
				# The live line on a terminal, rewritten in place with the time spent; elsewhere (a log, a script) each one a line
				if [[ -t 2 ]]; then
					printf '\r\033[K» %s · %d:%02d' "${line:0:$((${COLUMNS:-100} - 12))}" $(((SECONDS - started) / 60)) $(((SECONDS - started) % 60)) >&2
					pending=1
				else
					printf '%s\n' "opensim: $line" >&2
				fi
			else
				[[ -n $pending ]] && printf '\r\033[K' >&2
				pending=
				printf '%s\n' "opensim: $line" >&2
			fi
		done < <(tail -c +"$((shown + 1))" "$errors" | head -c "$((size - shown))")
	fi
	shown=$size
	return 0
}
# The live line of a step of root, on the error output as it is when the step runs (what the step says is kept, said on a failure)
exec 3>&2
# A command of a step of root: as it is when this runs as root (a migration), else through sudo (a new grid's website)
as_root() {
	if [[ $(id -u) -eq 0 ]]; then "$@"; else sudo "$@"; fi
}
# A line of a step of root: rewritten in place on a terminal, else a line each (a log, a script)
step_line() { # text
	if [[ -t 3 ]]; then
		printf '\r\033[K» %s' "$1" >&3
		pending=1
	else
		printf '%s\n' "$1" >&3
	fi
}
# A step of root of the scenario of the engine, by its NAME, from this closed list only, with the arguments it checks: never a command,
# a path or a package it is handed otherwise; any other name is refused. The live line says it with its label ([1/8] Stop).
# The layout of the install made as root (its account, its folders, w4os.conf), the folders given (SETTING=PATH) written first
make_layout() { # [--follow] [SETTING=PATH]...
	# From a clone (no package made an account): the folders are the caller's, who owns the clone and runs the instances;
	# root alone gets the account of the suite, which must then be able to read the clone
	local owner=
	[[ "$CLI_ROOT" == /usr/* ]] || owner=${SUDO_USER:-$(id -un)}
	[[ "$owner" != root ]] || owner=
	as_root env W4OS_AUTOLOAD="${W4OS_AUTOLOAD:-}" ${owner:+OPENSIM_SYSTEM_USER="$owner"} php "$(dirname "$(realpath "$OPENSIM_API")")/opensim-layout.php" "$@" || return 1
	if [[ -z "$owner" && "$CLI_ROOT" != /usr/* ]]; then
		owner=$(run system-user 2>/dev/null) || owner=
		[[ -z "$owner" ]] || as_root sudo -u "$owner" test -x "$CLI_ROOT/bin/opensim" 2>/dev/null ||
			{ printf '%s\n' "The account $owner cannot read this clone: $CLI_ROOT." "Move the clone where it can read it" "Or run the install from your own account"; return 1; }
	fi
}
LEGACY_STARTERS=${OPENSIM_LEGACY_STARTERS:-/etc/cron.hourly/opensim /etc/systemd/system/opensim.service /etc/init.d/opensim}
root_step() { # name, args (JSON), label
	local name=$1 args=$2 label=$3 file pid config grid package option target
	case $name in
	set-aside-starters)
		step_line "$label: start at boot set aside"
		while IFS= read -r file; do
			[[ -n "$file" ]] || continue
			[[ " $LEGACY_STARTERS " == *" $file "* ]] || { echo "set-aside-starters: not a starter of the pre-existing install: $file"; return 1; }
			[[ ! -e "$file" ]] || mv -- "$file" "$file.w4os-disabled" || return 1
		done < <(jq -r '(.files // [])[]' <<<"$args")
		[[ ! -d /run/systemd/system ]] || systemctl daemon-reload || true
		;;
	stop-old-instances)
		# A config of the install of this machine, or of the location given: the OpenSim.ini of its bin folder (a core there), its Robust file
		local bin robust
		bin=$(jq -r '.location.bin // empty' <<<"$args")
		robust=$(jq -r '.location.robust // empty' <<<"$args")
		[[ -z "$bin" || -f "$bin/OpenSim.dll" || -f "$bin/OpenSim.exe" ]] || { echo "stop-old-instances: not an OpenSim bin folder: $bin"; return 1; }
		while IFS= read -r config; do
			[[ -n "$config" ]] || continue
			[[ -f "$config" && ( "$config" == "${W4OS_LEGACY_ROOT:-/opt/opensim}"/etc/*.ini || ( -n "$bin" && ( "$config" == "$bin/OpenSim.ini" || "$config" == "$robust" ) && "$config" == *.ini ) ) ]] ||
				{ echo "stop-old-instances: not a config of the pre-existing install: $config"; return 1; }
			target=$(readlink -f -- "$config")
			step_line "$label: $(basename "$config" .ini)"
			for pid in $(legacy_pids "$target"); do
				kill -TERM "$pid" 2>/dev/null || continue
				for _ in $(seq 1 60); do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
				! kill -0 "$pid" 2>/dev/null || { echo "process $pid ($config) did not stop"; return 1; }
			done
		done < <(jq -r '(.configs // [])[]' <<<"$args")
		;;
	give-ownership)
		# What was moved into the folders (a migration) is given to their account: the layout is asked to go through them
		step_line "$label"
		make_layout --follow || return 1
		;;
	set-folders)
		# The folders changed in a review: each a setting of the closed list and a full path, written in w4os.conf and made
		local key path
		local -a roots=()
		while IFS=$'\t' read -r key path; do
			[[ " EtcRoot VarRoot DataRoot LogsRoot CacheRoot BackupRoot CoreRoot " == *" $key "* && "$path" == /?* && "$path" != *[[:space:]]* && "$path/" != */../* ]] ||
				{ echo "set-folders: not a folder of the install: $key = $path"; return 1; }
			roots+=("$key=$path")
		done < <(jq -r '(.roots // {}) | to_entries[] | [.key, .value] | @tsv' <<<"$args")
		((${#roots[@]})) || { echo "set-folders: no folder given"; return 1; }
		step_line "$label"
		make_layout "${roots[@]}" || return 1
		;;
	install-service)
		# The start at boot of an install the package does not start (a clone): the unit of systemd, as root, started so that the
		# grids of the run are the service's from their first start, unless the run starts it by a step of its own (start: false);
		# on macOS the agent of launchd of the person
		step_line "$label"
		"$CLI_ROOT/bin/opensim" service --install </dev/null >/dev/null || return 1
		if [[ $(jq -r '.start' <<<"$args") != false && ${OPENSIM_SERVICE_KIND:-$(uname -s)} != Darwin && ${OPENSIM_SERVICE_KIND:-} != launchd && -d /run/systemd/system ]]; then
			as_root systemctl start opensim || { printf '%s\n' "opensim.service did not start." "systemctl status opensim"; return 1; }
		fi
		;;
	install-dotnet)
		# The .NET runtime the cores target, by the command that knows what each system has
		step_line "$label"
		as_root "$CLI_ROOT/bin/opensim" install-dotnet -y </dev/null || return 1
		;;
	install-packages)
		while IFS= read -r package; do
			[[ "$package" =~ ^(opensim-[0-9.]+-maptiles|w4os-site)$ ]] || { echo "install-packages: not a package of the scenario: $package"; return 1; }
			step_line "$label: $package"
			as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "$package" >/dev/null || return 1
		done < <(jq -r '(.packages // [])[]' <<<"$args")
		option=$(jq -r '.option // empty' <<<"$args")
		grid=$(jq -r '.grid // empty' <<<"$args")
		if [[ -n "$option" ]]; then
			[[ "$option" == map-warp3d && "$grid" =~ ^[a-z0-9_-]+$ ]] || { echo "install-packages: not an option of the scenario: $option"; return 1; }
			"$CLI_ROOT/bin/opensim" enable "$grid" "$option" || return 1
		fi
		;;
	install-website)
		grid=$(jq -r '.grid // empty' <<<"$args")
		[[ "$grid" =~ ^[a-z0-9_-]+$ ]] || { echo "install-website: not a grid: $grid"; return 1; }
		step_line "$label: $grid"
		# The yes to its line in the sites of Apache is the scenario's (asked before Start): a step never asks
		local edit=
		[[ "$(jq -r '.edit_vhosts // false' <<<"$args")" != true ]] || edit=--edit-vhosts
		as_root "$CLI_ROOT/bin/opensim" web "$grid" site --install $edit </dev/null || return 1
		;;
	db-admin)
		# The DB admin user: one that logs in kept as it is, else made when no account has its name (on any host), never changed
		# (one that exists and is refused is said: its password, or an account the server lets in from its own system user only);
		# then kept for the commands (OPENSIM_RC, else ~/.opensimrc)
		local user password client quoted
		user=$(jq -r '.user // empty' <<<"$args")
		password=$(jq -r '.password // empty' <<<"$args")
		[[ "$user" =~ ^[A-Za-z0-9_]{1,32}$ && -n "$password" ]] || { echo "db-admin: not a user: $user"; return 1; }
		step_line "$label: $user"
		client=$(command -v mariadb || command -v mysql) || { printf '%s\n' "No database client here: mariadb or mysql." "sudo apt install default-mysql-client"; return 1; }
		if ! MYSQL_PWD=$password "$client" -u "$user" -h localhost -Nse 'SELECT 1' >/dev/null 2>&1; then
			as_root "$client" -Nse 'SELECT 1' >/dev/null 2>&1 || { echo "No access to the database server as root."; return 1; }
			[[ -z "$(as_root "$client" -Nse "SELECT Host FROM mysql.user WHERE User='$user'" 2>/dev/null)" ]] || { echo "$user: login refused by the database server."; return 1; }
			quoted=${password//\'/\'\'}
			printf "SET SESSION sql_mode='NO_BACKSLASH_ESCAPES'; CREATE USER '%s'@'localhost' IDENTIFIED BY '%s'; GRANT ALL PRIVILEGES ON *.* TO '%s'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES;\n" "$user" "$quoted" "$user" |
				as_root "$client" >/dev/null 2>&1 || { echo "$user could not be made."; return 1; }
		fi
		keep_db_admin "$user" "$password" || { echo "$user made, its password not kept."; return 1; }
		;;
	restart-service)
		# Without the unit of the packages (an install from a clone, a machine without systemd) the grids are started as they are
		# by the command: nothing starts them at boot then
		if [[ -d /run/systemd/system ]] && systemctl cat opensim.service >/dev/null 2>&1; then
			step_line "$label: opensim.service"
			as_root systemctl restart opensim || { printf '%s\n' "opensim.service did not restart." "systemctl status opensim"; return 1; }
		else
			step_line "$label: opensim start"
			"$CLI_ROOT/bin/opensim" start </dev/null >/dev/null 2>&1 || { printf '%s\n' "the grids did not start." "opensim start"; return 1; }
		fi
		;;
	*)
		echo "unknown step $name: refused"
		return 1
		;;
	esac
}

# The account the DB admin user is kept for: the one of the instances, which makes the databases and the users of a grid without
# being root (root reaches the server by itself); root where the install has none
db_admin_owner() {
	local owner
	owner=$(run system-user 2>/dev/null) || owner=
	[[ -n "$owner" ]] && id "$owner" >/dev/null 2>&1 || owner=root
	printf '%s\n' "$owner"
}

# The DB admin user kept for the commands. Run by root: in the file of the machine (database-admin.rc beside w4os.conf), for the
# account of the instances alone. Else in the person's own rc file (OPENSIM_RC, else ~/.opensimrc), theirs
keep_db_admin() { # user, password
	local rc=${OPENSIM_RC:-$HOME/.opensimrc} tmp machine=${W4OS_MACHINE_RC_DIR:-/etc/w4os} owner
	if [[ $(id -u) -eq 0 ]]; then
		rc=$machine/database-admin.rc
		mkdir -p "$machine" || return 1
	fi
	tmp=$(mktemp "$rc.XXXXXX") || return 1
	[[ ! -e "$rc" ]] || grep -Ev '^export OPENSIM_DB_(HOST|ADMIN_USER|ADMIN_PASS)=' "$rc" >"$tmp" || true
	printf 'export OPENSIM_DB_HOST=localhost\nexport OPENSIM_DB_ADMIN_USER=%q\nexport OPENSIM_DB_ADMIN_PASS=%q\n' "$1" "$2" >>"$tmp"
	chmod 600 "$tmp" && mv -f "$tmp" "$rc" || return 1
	if [[ $(id -u) -eq 0 ]]; then
		owner=$(db_admin_owner)
		chown "$owner:$(id -gn "$owner")" "$rc" 2>/dev/null || true
	elif [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != root ]]; then
		chown "$SUDO_USER:$(id -gn "$SUDO_USER")" "$rc"
	fi
	export OPENSIM_DB_ADMIN_USER=$1 OPENSIM_DB_ADMIN_PASS=$2
}

# The processes that run a config (resolved): the -inifile each was given, quotes taken off, relative to its folder
legacy_pids() { # config, resolved
	local proc arg value previous cwd
	for proc in "${W4OS_LEGACY_PROC:-/proc}"/[0-9]*; do
		[[ -r "$proc/cmdline" ]] || continue
		value= previous=
		while IFS= read -r -d '' arg; do
			if [[ "$arg" == -inifile=* ]]; then value=${arg#-inifile=}; elif [[ "$previous" == -inifile ]]; then value=$arg; fi
			previous=$arg
		done <"$proc/cmdline" 2>/dev/null
		# Given none, a core reads the config of its folder named after it
		if [[ -z "$value" ]]; then
			case $(tr '\0' '\n' <"$proc/cmdline" 2>/dev/null) in
			*Robust.dll* | *Robust.exe*) value=Robust.ini ;;
			*OpenSim.dll* | *OpenSim.exe*) value=OpenSim.ini ;;
			*) continue ;;
			esac
		fi
		value=${value#[\'\"]}
		value=${value%[\'\"]}
		[[ "$value" == /* ]] || { cwd=$(readlink -- "$proc/cwd" 2>/dev/null) || continue; value=$cwd/$value; }
		[[ "$(readlink -f -- "$value")" == "$1" ]] && basename "$proc"
	done
	return 0
}

# The engine gave no screen: what it said (a problem: its status and title), and the errors it wrote that are not progress. Nothing else is done.
fail_engine() {
	local what
	what=$(jq -r 'select(.status) | "HTTP \(.status) \(.title)\(if .detail then ": " + .detail else "" end)"' 2>/dev/null <<<"$1")
	die "The engine does not answer as it should: ${what:-$1}$(grep -v '^opensim: ' "$errors" | sed 's/^/\n  /')"
}

# A prepared configuration applied by root: its DB admin user (else OPENSIM_DB_ADMIN_USER, else opensim_admin) made or checked by its
# step first, a server of this machine being there
if [[ -n "$apply_file" ]]; then
	sql_client=$(command -v mariadb || command -v mysql || true)
	if [[ $(id -u) -eq 0 && -n "$sql_client" ]]; then
		admin_args=$(jq -c --arg user "${OPENSIM_DB_ADMIN_USER:-opensim_admin}" --arg password "${OPENSIM_DB_ADMIN_PASS:-$(openssl rand -hex 16)}" \
			'{user: ((.answers.admin_user // "") | if . == "" then $user else . end), password: ((.answers.admin_password // "") | if . == "" then $password else . end)}' <<<"$apply_input") ||
			die "invalid prepared setup JSON"
		if ! MYSQL_PWD=$(jq -r .password <<<"$admin_args") "$sql_client" -u "$(jq -r .user <<<"$admin_args")" -h localhost -Nse 'SELECT 1' >/dev/null 2>&1; then
			admin_said=$(root_step db-admin "$admin_args" "DB admin user" 3>/dev/null) || die "$(tail -n 1 <<<"$admin_said")"
		fi
		export OPENSIM_DB_ADMIN_USER OPENSIM_DB_ADMIN_PASS
		OPENSIM_DB_ADMIN_USER=$(jq -r .user <<<"$admin_args") OPENSIM_DB_ADMIN_PASS=$(jq -r .password <<<"$admin_args")
	fi
	apply_request=$(jq -ce --rawfile admin_user <(printf '%s' "${OPENSIM_DB_ADMIN_USER:-}") --rawfile admin_password <(printf '%s' "${OPENSIM_DB_ADMIN_PASS:-}") "$apply_filter" <<<"$apply_input") ||
		die "invalid prepared setup JSON"
fi
adoption_required=$(jq -r '(.existing_region // "") != ""' <<<"$setup_prefill")
if [[ -n "$apply_request" ]]; then
	adoption_required=$(jq -r '.data.attributes.configuration | (.answers.existing_region // .setup.simulators[0].regions[0].source // "") != ""' <<<"$apply_request")
fi
if [[ "$adoption_required" == true ]]; then
	reply=$(engine POST /setups/quick --data=- <<<'{"data":{"type":"setups","attributes":{}}}' 2>"$errors") || fail_engine "$reply"
	jq -e '.data.attributes.capabilities | arrays | index("existing_region") != null' <<<"$reply" >/dev/null || die "The engine does not support existing-region setup."$'\n'"sudo apt install w4os-engine"
fi

# The answers the scenario takes without anybody, as it describes them
if [[ -n "${setup_keys:-}" ]]; then
	[[ -n "${setup_legacy:-}" ]] || die "--config-keys goes with --legacy"
	reply=$(engine POST /setups/steps --data=- <<<'{"data":{"type":"steps","attributes":{"existing":true,"keys":true}}}' 2>"$errors") || fail_engine "$reply"
	jq -er '.data.attributes.keys[] | [.name, (.values | if type == "array" then join("|") else . end), (if .default == "" then "-" else .default end), .label] | @tsv' <<<"$reply" | column -t -s $'\t' || fail_engine "$reply"
	exit 0
fi
[[ -z "${setup_unattended:-}" || -n "${setup_legacy:-}" ]] || die "--unattended goes with --legacy"

# An install made before the files of the machine: the DB admin user a person's file gave is kept in the machine's too, the old
# file left as it is and still read
if [[ $(id -u) -eq 0 && -n "${OPENSIM_DB_ADMIN_USER:-}" && -n "${OPENSIM_DB_ADMIN_PASS:-}" && -d "${W4OS_MACHINE_RC_DIR:-/etc/w4os}" && ! -e "${W4OS_MACHINE_RC_DIR:-/etc/w4os}/database-admin.rc" ]]; then
	keep_db_admin "$OPENSIM_DB_ADMIN_USER" "$OPENSIM_DB_ADMIN_PASS" || true
fi
# A file of the machine kept for root alone by an install of before: given to the account of the instances, whose it is
if [[ $(id -u) -eq 0 && -f "${W4OS_MACHINE_RC_DIR:-/etc/w4os}/database-admin.rc" ]]; then
	admin_owner=$(db_admin_owner)
	[[ "$admin_owner" == root ]] || chown "$admin_owner:$(id -gn "$admin_owner")" "${W4OS_MACHINE_RC_DIR:-/etc/w4os}/database-admin.rc" 2>/dev/null || true
fi

while :; do
	request=$(jq -c --rawfile state <(printf '%s' "$state") --arg button "$button" --arg mode "$setup_mode" --slurpfile prefill <(printf '%s' "$setup_prefill") --argjson occupied_ports "${setup_occupied_ports:-null}" \
		'{data: {type: "steps", attributes: ({state: $state, button: $button, answers: (. + ($prefill[0] | {existing_region,hostname,oar,dump,show_passwords} | with_entries(select(.value != null)))), mode: $mode} + (if $occupied_ports == null then {} else {occupied_ports: $occupied_ports} end))}}' <<<"$answers")
	# The prepared configuration sent once: the requests after it are the ones of its run (its website)
	[[ -z "$apply_request" ]] || { request=$apply_request; apply_request=; }
	# The first request asks for the scenario of an install of before the kit, when there is one
	[[ -z "${setup_legacy:-}" || -n "$state" ]] || request=$(jq -c '.data.attributes.existing = true' <<<"$request")
	# Nobody there: every answer at once, the ones of --config (the scenario checks them and takes a default for the others)
	[[ -z "${setup_unattended:-}" || -n "$state" ]] || request=$(jq -c --argjson prefill "$setup_prefill" '.data.attributes.unattended = true | .data.attributes.answers = $prefill' <<<"$request")
	# What the engine tells while it works (lines starting with "opensim: ") is shown as it comes. Its answer goes to a file and its
	# error output to another that is read while it runs: the instances it starts keep both open, a pipe would never end
	: >"$errors"
	# Its terminal (fd 3, the live lines of this command) is not the engine's: an instance it starts would keep it
	engine POST /setups/steps --data=- <<<"$request" >"$answer" 2>>"$errors" 3>&- &
	pid=$!
	shown=0
	while kill -0 "$pid" 2>/dev/null; do
		show_progress
		sleep 0.3
	done
	wait "$pid" 2>/dev/null
	show_progress
	reply=$(<"$answer")
	screen=$(jq -c '.data.attributes' 2>/dev/null <<<"$reply") && [[ "$(jq -r '.action // empty' <<<"$screen")" != "" ]] ||
		fail_engine "$reply"
	if [[ "$setup_mode" == prepare && "$(jq -r '.mode // empty' <<<"$screen")" != prepare ]]; then
		die "The engine does not support setup preparation."$'\n'"sudo apt install w4os-engine"
	fi
	if [[ "$(jq -r '.action + ":" + (.kind // "")' <<<"$screen")" == screen:menu && -n "$setup_prefill_type" ]]; then
		state=$(jq -r '.state' <<<"$screen")
		answers=$(jq -c '{type,existing_region,hostname,login_uri,oar,dump,show_passwords} | with_entries(select(.value != null))' <<<"$setup_prefill")
		setup_prefill_type=
		continue
	fi
	# What the engine did with this request, left as a line (✓ OpenSimulator 0.9.3.0) before what follows
	done_said=$(jq -r '.done // empty' <<<"$screen")
	if [[ -n "$done_said" ]]; then
		[[ -z ${pending:-} ]] || { printf '\r\033[K' >&2; pending=; }
		# One line for each thing done
		sed 's/^/✓ /' <<<"$done_said" >&2
	fi
	case "$(jq -r .action <<<"$screen")" in
	screen)
		# The live line of the request done: its place for the screen
		[[ -z ${pending:-} ]] || { printf '\r\033[K' >&2; pending=; }
		[[ -z "$apply_file" ]] || die "The engine could not apply the prepared configuration: $(jq -r '.notice // empty' <<<"$screen")"
		case "$(jq -r .kind <<<"$screen")" in
			# A value of the configuration, false and 0 too (jq's // would take false for nothing): a boolean as yes or no, and a
			# field of yes and no takes true/false/1/0/on/off as one of them
			form) screen=$(jq -c --slurpfile prefill <(printf '%s' "$setup_prefill") "$PREFILL_YN"'$prefill[0] as $prefill | .fields |= map(.name as $n | .options as $o | if ($prefill | has($n)) and $prefill[$n] != null then .value = ($prefill[$n] | yn | yesno($o)) else . end)' <<<"$screen") ;;
			checks) screen=$(jq -c --slurpfile prefill <(printf '%s' "$setup_prefill") "$PREFILL_YN"'$prefill[0] as $prefill | .items |= map(.name as $n | if ($prefill | has($n)) and $prefill[$n] != null then .checked = (($prefill[$n] | yn | ascii_downcase) as $s | $s == "yes" or $s == "true" or $s == "1" or $s == "on" or $s == "y") else . end)' <<<"$screen") ;;
		esac
		ui_screen "$screen"
		;;
	prepared)
		[[ "$setup_mode" == prepare ]] || die "The engine returned an unexpected prepared configuration"
		prepared_tmp=$(mktemp "${prepare_file}.XXXXXXXX") || die "cannot write setup configuration: $prepare_file"
		jq -ce '.configuration | select(type == "object" and (.answers | type) == "object")' <<<"$screen" >"$prepared_tmp" || die "The engine returned an invalid setup configuration"
		chmod 600 "$prepared_tmp" && mv -f "$prepared_tmp" "$prepare_file" || die "cannot save setup configuration: $prepare_file"
		prepared_tmp=
		say "Setup configuration saved in $prepare_file"
		exit 0
		;;
	quit)
		[[ "$setup_mode" != prepare ]] || die "The engine ended preparation without a configuration"
		# The live line done: its place for what follows
		[[ -z ${pending:-} ]] || printf '\r\033[K' >&2
		# Its summary kept for the caller that says it last, after its own steps (kickstart: the website), else said now
		if [[ -n "${OPENSIM_SETUP_END:-}" ]] && jq -r .message <<<"$screen" >"$OPENSIM_SETUP_END" 2>/dev/null; then
			exit 0
		fi
		jq -r .message <<<"$screen"
		exit 0
		;;
	step)
		# A step of the run: the engine's, done at the next request (its live line then), or one of root, run here by its name
		state=$(jq -r .state <<<"$screen")
		STEP_LABELS=$(jq -r '(.labels // [])[]' <<<"$screen")
		answers='{}'
		button=next
		if [[ "$(jq -r .step.root <<<"$screen")" == true ]]; then
			step_status=0
			step_said=$(root_step "$(jq -r .step.name <<<"$screen")" "$(jq -c '.step.args // {}' <<<"$screen")" "$(jq -r '"[\(.step.number)/\(.step.count)] \(.step.label)"' <<<"$screen")" 2>&1) || step_status=$?
			# The folders made: the engine of a setup run by root goes on as the account they were given to (none before them). Never
			# the scenario of a pre-existing install (--legacy), which root runs to its end: its data are another account's
			if ((step_status == 0)) && [[ "$(jq -r .step.name <<<"$screen")" =~ ^(give-ownership|set-folders)$ && $(id -u) -eq 0 && -n "${OPENSIM_SETUP_ENGINE_AS+set}" && -z "$OPENSIM_SETUP_ENGINE_AS" && -z "${setup_legacy:-}" ]]; then
				OPENSIM_SETUP_ENGINE_AS=$(run system-user 2>/dev/null) || OPENSIM_SETUP_ENGINE_AS=
				[[ -z "$OPENSIM_SETUP_ENGINE_AS" ]] || engine() { system_user=$OPENSIM_SETUP_ENGINE_AS as_system_user "$OPENSIM_API" "$@"; }
			fi
			# Its live line, written by the step in a subshell, cleared here: the next screen takes its place
			[[ ! -t 3 ]] || printf '\r\033[K' >&3
			pending=
			# A step that stands alone (the folders, the runtime) leaves its line once done
			done_said=$(jq -r '.step.done // empty' <<<"$screen")
			((step_status != 0)) || [[ -z "$done_said" ]] || printf '✓ %s\n' "$done_said" >&3
			if ((step_status != 0)); then
				button=failed
				answers=$(jq -cn --arg text "$(tail -n 3 <<<"$step_said")" '{error_text: $text}')
			fi
		else
			stage=$(jq -r '"[\(.step.number)/\(.step.count)] \(.step.label)"' <<<"$screen")
		fi
		;;
	handoff)
		# What this command runs itself still (in place): said to its caller, which runs it
		[[ -z ${pending:-} ]] || printf '\r\033[K' >&2
		printf 'handoff: %s\n' "$(jq -r .path <<<"$screen")"
		exit 3
		;;
	abort)
		[[ -z ${pending:-} ]] || printf '\r\033[K' >&2
		# A stop the person asked for: its line as it is, not an error (exit 4)
		if [[ "$(jq -r '.stopped // false' <<<"$screen")" == true ]]; then
			printf '%s\n' "$(jq -r .error <<<"$screen")" >&2
			exit 4
		fi
		error "$(jq -r .error <<<"$screen")"
		exit "$(jq -r '.code // 1' <<<"$screen")"
		;;
	*) die "The engine asks for an action this command does not know: $(jq -r .action <<<"$screen")" ;;
	esac
done
