# What the commands share: bash-tools, the engine and the rc file. Sourced by the commands, not run.
#
# The rules and the work are the engine's (w4os-api): this tool shows the questions, gives the answers to the engine and shows what
# it says. bash-tools and the engine are dependencies (composer, or the packages that link them in vendor/magicoli), found in vendor/
# of this project; OPENSIM_API names another engine, which is how the tests use a stand-in.

_here=$(dirname "$(realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")
CLI_ROOT=$(cd "$_here/../.." && pwd)
unset _here

_helpers="$CLI_ROOT/vendor/magicoli/bash-tools/bin/bash-helpers"
[[ -f "$_helpers" ]] || {
	echo "${0##*/}: bash-tools is not installed (composer install in $CLI_ROOT)" >&2
	exit 1
}
# shellcheck disable=SC1090
source "$_helpers"
unset _helpers
# -v and -q of the command line, for the engine and the commands it runs
[[ "${DEBUG:-}" != yes ]] || export DEBUG
[[ "${QUIET:-}" != yes ]] || export QUIET

OPENSIM_API=${OPENSIM_API:-$CLI_ROOT/vendor/w4os/w4os-engine/bin/w4os-api}
[[ -x "$OPENSIM_API" ]] || die "The engine is not installed (composer install in $CLI_ROOT)"
require jq

# The rc file, for any script of the ecosystem: it may fix the PATH (which php)
if [[ -r "$(dirname "$OPENSIM_API")/../lib/rc-helpers" ]]; then
	# shellcheck disable=SC1091
	source "$(dirname "$OPENSIM_API")/../lib/rc-helpers" && read_rc
fi

# The version of the command line: the package that installed it, else its git version in a clone, else the one being worked on
cli_version() {
	local version=
	if [[ "$CLI_ROOT" == /usr/share/w4os-cli* ]] && command -v dpkg-query >/dev/null 2>&1; then
		version=$(dpkg-query -W -f='${Version}' w4os-cli 2>/dev/null) || version=
	fi
	[[ -n "$version" || ! -e "$CLI_ROOT/.git" ]] || version=$(git -C "$CLI_ROOT" describe --tags --always --dirty 2>/dev/null) || version=
	[[ -n "$version" || ! -f "$CLI_ROOT/.version" ]] || version="$(<"$CLI_ROOT/.version") (development)"
	printf '%s\n' "${version:-unknown}"
}

# Ask the engine: engine POST /setups/quick --data=- < body
engine() {
	"$OPENSIM_API" "$@"
}

# The accounts of the install in w4os.conf (SystemUser, WebUser, WebGroup), one a line
install_accounts() {
	sed -nE 's/^[[:space:]]*(SystemUser|WebUser|WebGroup)[[:space:]]*=[[:space:]]*"?([^";[:space:]]*).*/\1=\2/p' "${OPENSIM_CONF:-/etc/w4os/w4os.conf}" 2>/dev/null | sort -u
}

# The accounts of the install changed since BEFORE (install_accounts; an import of an install that exists takes its own): its folders
# and the units of the suite made to follow them, as root (the system layout of the engine), by the caller, not the account of the
# instances
follow_accounts() { # accounts before, [restart: the instances just started are made the service's account's]
	local now user
	now=$(install_accounts)
	[[ "$now" != "$1" ]] || return 0
	user=$(sed -n 's/^SystemUser=//p' <<<"$now" | head -1)
	as_root php "$(dirname "$(realpath "$OPENSIM_API")")/opensim-layout.php" || die "could not make the service run as $user"
	if [[ "${2:-}" == restart && -d /run/systemd/system ]]; then
		say "Restarting opensim.service: its instances run as $user from now on"
		as_root systemctl restart opensim || die "could not restart opensim.service: systemctl status opensim"
		return 0
	fi
	say "The service runs as $user from its next start (sudo systemctl restart opensim, once the grids may stop)"
}

# Act on this machine through the engine (src/php/run.php): run COMMAND [ARGUMENTS]; its status is the one of the command
run() {
	php "$CLI_ROOT/src/php/run.php" "$@"
}

say() { printf '%s\n' "$*"; }
debug_log() {
	[ -n "${DEBUG}" ] || return 0
	[ "$DEBUG" = "yes" ] || return 0
	say "$PGM: [DEBUG] $*" >&2
}
error() {
	say "$PGM: [ERROR] $*" >&2
}
die() {
	error "$*"
	exit 1
}

# A question for the person at the terminal, even when this script comes from a pipe; yes when nobody can answer
ask() {
	[[ -n "$ASSUME_YES" ]] && return 0
	[[ -r /dev/tty ]] || return 0
	local answer
	read -r -p "$1 [Y/n] " answer </dev/tty
	[[ ! $answer =~ ^[Nn] ]]
}

as_root() {
	if [[ $(id -u) -eq 0 ]]; then
		"$@"
	elif command -v sudo >/dev/null 2>&1; then
		sudo --preserve-env=${PRESERVE_ENV:-} "$@"
	else
		die "this needs administrator rights: run it as root, or install sudo"
	fi
}

as_system_user() {
	system_user=${system_user:-}
	if [[ -z "$system_user" || "$(id -un)" == "$system_user" ]]; then
		"$@"
	# elif [[ $(id -u) -eq 0 ]]; then
	# 	runuser -u "$system_user" -- "$@"
	elif command -v sudo >/dev/null 2>&1; then
		sudo -u ${system_user} --preserve-env=${PRESERVE_ENV:-} "$@"
	else
		die "this needs administrator rights: run it as root, or install sudo"
	fi
}

# The accounts of a list: the list read as its caller and sent to the import (run as the user of the instances), the result, with the
# passwords made, kept for the caller only (mode 600)
import_accounts() {
	local -a arguments=()
	local list= result= apply= csv status=0 runner=as_system_user
	while (($#)); do
		case "$1" in
		--accounts)
			(($# > 1)) || die "--accounts requires the list of the accounts"
			list=$2
			shift 2
			;;
		--accounts=*) list=${1#*=}; shift ;;
		--result)
			(($# > 1)) || die "--result requires a file"
			result=$2
			shift 2
			;;
		--result=*) result=${1#*=}; shift ;;
		--apply) apply=yes; arguments+=("$1"); shift ;;
		# A grid this install does not manage: its config is the caller's to read, the import runs as them
		--robust | --robust=*) runner=; arguments+=("$1"); shift ;;
		*) arguments+=("$1"); shift ;;
		esac
	done
	[[ -r "$list" ]] || die "cannot read $list"
	# The format by the extension of the list, unless it is given
	if [[ " ${arguments[*]} " != *" --format"* ]]; then
		case "${list,,}" in
		*.yaml | *.yml) arguments+=(--format yaml) ;;
		*.json) arguments+=(--format json) ;;
		*.csv) arguments+=(--format csv) ;;
		esac
	fi
	csv=$($runner "$CLI_ROOT/libexec/import" --accounts - ${arguments[@]+"${arguments[@]}"} <"$list") || status=$?
	if [[ -n "$apply" && -n "$csv" ]]; then
		result=${result:-accounts-result-$(date +%Y%m%d-%H%M%S).csv}
		(umask 077 && printf '%s\n' "$csv" >"$result") || die "could not write $result"
		chmod 600 "$result"
		say "Result (with the passwords made here): $result"
	fi
	return "$status"
}

# Run a command as the system user with the files of some options (--oar FILE, --dump FILE) it can read: their own path when it
# reads them, else a copy in a folder of its own (in /var/tmp: an archive can be large), removed once the command is over
as_system_user_with_files() { # "OPTION..." COMMAND [ARGUMENTS...]
	local options=" $1 " status=0 index file copies= option
	shift
	local -a arguments=("$@")
	for ((index = 1; index < ${#arguments[@]}; index++)); do
		option=${arguments[index]%%=*}
		[[ "$options" == *" $option "* ]] || continue
		if [[ "${arguments[index]}" == *=* ]]; then
			file=${arguments[index]#*=}
		else
			((index + 1 < ${#arguments[@]})) || die "$option requires a file"
			file=${arguments[index + 1]}
		fi
		[[ -r "$file" ]] || die "cannot read $file"
		file=$(realpath "$file")
		if ! as_system_user test -r "$file"; then
			[[ -n "$copies" ]] || copies=$(as_system_user mktemp -d /var/tmp/opensim-files.XXXXXXXX) || die "could not make a folder for $file"
			as_system_user sh -c 'umask 077; cat > "$1"' copy "$copies/$(basename "$file")" <"$file" || {
				as_system_user rm -rf -- "$copies" || true
				die "could not give $file to the account $system_user"
			}
			file=$copies/$(basename "$file")
		fi
		if [[ "${arguments[index]}" == *=* ]]; then
			arguments[index]=$option=$file
		else
			arguments[index + 1]=$file
			((index += 1))
		fi
	done
	as_system_user "${arguments[@]}" || status=$?
	[[ -z "$copies" ]] || as_system_user rm -rf -- "$copies" || true
	return "$status"
}

# Read private setup inputs as their caller and pass them to the service account without changing their permissions.
run_setup() {
	local -a arguments=("$@") inputs=() indexes=()
	local index position input_file input_dir= destination status=0 option
	if [[ -z "${system_user:-}" || "$(id -un)" == "$system_user" ]]; then
		"$CLI_ROOT/libexec/setup" "$@"
		return $?
	fi
	for ((index = 0; index < ${#arguments[@]}; index++)); do
		input_file=
		case "${arguments[index]}" in
			--apply)
				((index + 1 < ${#arguments[@]})) || die "--apply requires a JSON file"
				input_file=${arguments[index+1]}; arguments[index+1]=- ;;
			--apply=*) input_file=${arguments[index]#*=}; arguments[index]=--apply=- ;;
		esac
		if [[ -n "$input_file" && "$input_file" != - ]]; then
			[[ -r "$input_file" ]] || die "cannot read prepared setup: $input_file"
			setup_client "${arguments[@]}" <"$input_file"
			return $?
		fi
	done
	for ((index = 0; index < ${#arguments[@]}; index++)); do
		case "${arguments[index]}" in
			--config | --region-config | --oar | --dump)
				option=${arguments[index]}
				((index + 1 < ${#arguments[@]})) || die "$option requires a file"
				input_file=${arguments[index+1]} ;;
			--config=* | --region-config=* | --oar=* | --dump=*) input_file=${arguments[index]#*=} ;;
			*) continue ;;
		esac
		[[ -r "$input_file" ]] || die "cannot read setup input: $input_file"
		# An archive or a dump the account reads is given as it is: it can be large
		case "${arguments[index]}" in
			--oar | --dump | --oar=* | --dump=*)
				if as_system_user test -r "$(realpath "$input_file")"; then
					case "${arguments[index]}" in
						*=*) arguments[index]=${arguments[index]%%=*}=$(realpath "$input_file") ;;
						*) arguments[index+1]=$(realpath "$input_file"); ((index += 1)) ;;
					esac
					continue
				fi ;;
		esac
		inputs+=("$input_file"); indexes+=("$index")
		[[ "${arguments[index]}" == *=* ]] || ((index += 1))
	done
	if ((${#inputs[@]})); then
		input_dir=$(as_system_user mktemp -d /var/tmp/opensim-setup.XXXXXXXX) || die "could not create private setup inputs"
	fi
	for ((position = 0; position < ${#inputs[@]}; position++)); do
		index=${indexes[position]}
		destination=$input_dir/input-$position
		if ! as_system_user sh -c 'umask 077; cat > "$1"' setup "$destination" <"${inputs[position]}"; then
			as_system_user rm -rf -- "$input_dir" || true
			die "could not transfer setup input: ${inputs[position]}"
		fi
		case "${arguments[index]}" in
			*=*) option=${arguments[index]%%=*}; arguments[index]=$option=$destination ;;
			*) arguments[index+1]=$destination ;;
		esac
	done
	setup_client "${arguments[@]}" || status=$?
	[[ -z "$input_dir" ]] || as_system_user rm -rf -- "$input_dir" || true
	return "$status"
}

# The setup's client: run by root, it stays root (the steps of root of the run are its own: the website) and only the engine runs as
# the system user, whose files it writes; else all of it as the system user
setup_client() {
	if [[ $(id -u) -eq 0 ]]; then
		OPENSIM_SETUP_ENGINE_AS=$system_user "$CLI_ROOT/libexec/setup" "$@"
	else
		as_system_user "$CLI_ROOT/libexec/setup" "$@"
	fi
}

# Apply a setup file through the engine (POST /setups/files): its text, plan or apply; shows the plan or what was written
setup_file() { # file mode
	local reply
	reply=$(jq -Rsc --arg mode "$2" '{data: {type: "files", attributes: {text: ., mode: $mode}}}' <"$1" | setup_file_engine POST /setups/files --data=-)
	setup_file_report "$reply"
}

# The answer of POST /setups/files as lines: each simulator and region, what is written, what is left to do
setup_file_report() { # reply
	jq -e '.data.attributes' <<<"$1" >/dev/null 2>&1 || die "$(setup_file_refusal "$1")"
	jq -r '.data.attributes |
		"Grid \(.grid)",
		(.steps[] |
			(if .kind == "simulator" then "Simulator \(.simulator) (\(.slug)): \(.config), http \(.ports.http), database \(.database.name) @ \(.database.host)" + (if .estate then ", estate \(.estate.name)" + (if .estate.owner then " (\(.estate.owner))" else "" end) else "" end) else "Region of \(.slug):" end),
			(if .region then "  \(.region.name) at \(.region.location), \(.region.size) m, port \(.region.port)" + (if (.region.roles | length) > 0 then ", " + (.region.roles | join(", ")) else "" end) + (if .region.existing then ", taken over from the grid (UUID \(.region.uuid))" else "" end) + (if .region.oar then ", loaded with \(.region.oar)" elif .region.dump then ", its database made from \(.region.dump)" else "" end) + ": \(.region.file)" else empty end)),
		(if (.problems // {}) | length > 0 then "Problems, to settle before it can be written:", (.problems | to_entries[] | "  \(.value)") else empty end),
		(if .applied then "Written:" else "Would write:" end),
		(.writes[] | "  \(.)"),
		"",
		(if .applied then ((.notes // [])[] | "  \(if type == "object" then .detail else . end)") else empty end),
		(if .applied then ((if (.reminders | length) > 0 then "Then:" else empty end), (.reminders[] | "  \(if type == "object" then .detail else . end)")) else "Nothing written. Add --apply." end)' <<<"$1"
}

# What the engine refused a setup file for, in the words of the command: the field paths of the file it was made into never said
setup_file_refusal() { # reply
	local detail
	detail=$(jq -r 'if .detail then .detail else (.title // "the engine did not answer") end' <<<"$1" 2>/dev/null) || detail=$1
	if [[ "$detail" =~ simulators\.[0-9]+\.database\.(user|password)\ is\ required ]]; then
		echo "No database account for the new simulator: its grid names none. Set OPENSIM_DB_USER and OPENSIM_DB_PASS."
		return
	fi
	# The problems one by one, without the place of each in the file
	sed -E 's/^the setup has problems: //; s/(^|; )file\.[0-9]+: /\1/g; s/(^|; )[a-z_]+(\.[0-9a-z_]+)+: /\1/g' <<<"$detail"
}

# The engine asked for a setup file: its answer on the output, what it says of a refusal kept (the command says it once, in its words),
# shown only when it gave no answer
setup_file_engine() { # engine arguments...
	local said reply
	said=$(mktemp)
	reply=$(engine "$@" 2>"$said") || true
	[[ -n "$reply" ]] || cat "$said" >&2
	rm -f "$said"
	printf '%s' "$reply"
}
