#!/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 an install of before the kit (/opt/opensim), its scenario: migrate it, run it in place, or a new grid
  --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)
  --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: .}}}
	'
	setup_apply_request() {
		jq -ce --rawfile admin_user <(printf '%s' "${OPENSIM_DB_ADMIN_USER:-}") --rawfile admin_password <(printf '%s' "${OPENSIM_DB_ADMIN_PASS:-}") "$apply_filter"
	}
	if [[ "$apply_file" == - ]]; then
		apply_request=$(setup_apply_request) || die "cannot read prepared setup from standard input"
	else
		[[ -r "$apply_file" ]] || die "cannot read prepared setup: $apply_file"
		apply_request=$(setup_apply_request <"$apply_file") || die "invalid prepared setup JSON"
	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).
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 an install of before the kit: $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)
		while IFS= read -r config; do
			[[ -n "$config" ]] || continue
			[[ "$config" == "${W4OS_LEGACY_ROOT:-/opt/opensim}"/etc/*.ini && -f "$config" ]] || { echo "stop-old-instances: not a config of the install of before the kit: $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)
		step_line "$label"
		php "$(dirname "$(realpath "$OPENSIM_API")")/opensim-layout.php" || 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"
			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
		;;
	restart-service)
		step_line "$label: opensim.service"
		[[ -d /run/systemd/system ]] || { echo "restart-service: no systemd here: opensim start starts the grids"; return 1; }
		systemctl restart opensim || { echo "opensim.service did not restart: systemctl status opensim"; return 1; }
		;;
	*)
		echo "unknown step $name: refused"
		return 1
		;;
	esac
}

# 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
		[[ -n "$value" ]] || continue
		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  /')"
}

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; update 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"

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"
	engine POST /setups/steps --data=- <<<"$request" >"$answer" 2>>"$errors" &
	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; update 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
	case "$(jq -r .action <<<"$screen")" in
	screen)
		[[ -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=$?
			[[ -z ${pending:-} ]] || { printf '\r\033[K' >&2; pending=; }
			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
		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
