#!/usr/bin/env bash
# opensim COMMAND [ARGUMENTS]: set up and manage OpenSimulator (see README.md). The commands are in libexec/.

set -e
here=$(dirname "$(realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")
libexec=$(cd "$here/../libexec" && pwd)

COMMANDOPTS=service,setup,import,region,simulator,settings,address,posts,diagnostics,status,ports,start,stop,restart,console,screen,enable,disable,web,next,ban,save,load,backup,restore,oar,api,api-key,rest,install-dotnet,module
HELP=$(
	cat <<USAGE

  setup           make a grid, a standalone or a simulator that joins a grid
  status          the instances of this machine, running or not
  ports           list instance ports, publishing options or firewall rules
  start           start grids and simulators
  stop            stop grids and simulators
  restart         stop, then start grids and simulators
  console|screen  attach to the console of a running instance
  enable|disable  enable or disable instances and grid features
  web             inspect grid services and print web-server snippets
  import          apply a setup file, or bring a simulator of another install into a grid (planned, --apply writes)
  region add      give a region to a simulator of a grid (planned, --apply writes)
  simulator add   make a simulator in a grid with its first region (planned, --apply writes)
  settings        read or change the settings pages of a grid (economy, search, guide...)
  address         change the host, the port or the site of a grid in every file of it (planned, --apply writes)
  posts           list or delete the posts of the avatars of a grid
  diagnostics     print the diagnostics of a grid, as its sites show them
  next            find free ports or region locations
  ban             prepare user cleanup and estate ban files
  save|load       save or restore IAR and OAR archives
  oar             pack, read, check or unpack an archive of regions (OAR)
  backup          back up grid configuration, data, and databases
  restore         put a backup back on this machine (planned, --apply writes)
  api             ask the engine API of this machine (opensim api GET /grids)
  api-key         make, list or revoke the keys of the engine API
  rest            use the remote OpenSim console client
  install-dotnet  install the .NET runtime OpenSimulator needs
  module          enable or disable a module for the install (opensim module enable gloebit)

System information
  --version [-v]         the version of the command line; with -v, of everything that matters here (engine, helpers, site, cores)
  --layout --format=env  print the resolved layout and identities as shell exports
USAGE
)
# Command help uses the command's own usage, before dispatch can prepare a setup or elevate privileges: --help anywhere, -h right
# after the command (later, -h is an option of the command: the home URL of an archive)
if [[ -n "${1:-}" && ",$COMMANDOPTS," == *",$1,"* && -x "$libexec/$1" ]]; then
	[[ "${2:-}" != -h ]] || exec "$libexec/$1" "${@:2}"
	for argument in "${@:2}"; do
		[[ "$argument" != --help ]] || exec "$libexec/$1" "${@:2}"
	done
fi
# The command as it was typed, for a message that gives it again with one more option
OPENSIM_AGAIN=opensim
for argument in "$@"; do OPENSIM_AGAIN+=" $(printf '%q' "$argument")"; done
export OPENSIM_AGAIN
export PRESERVE_ENV=OPENSIM_AGAIN,W4OS_RC_GIVEN,PATH,OPENSIM_API,W4OS_AUTOLOAD,CONTAINER_CONNECTION,DEFAULT_OWNER_NAME,DEFAULT_OWNER_PASSWORD,DOTNET_SYSTEM_NET_DISABLEIPV6,OPENSIM_DB_ADMIN_PASS,OPENSIM_DB_ADMIN_USER,OPENSIM_DB_HOST,OPENSIM_DB_NAME,OPENSIM_DB_PASS,OPENSIM_DB_PORT,OPENSIM_DB_USER,OPENSIM_REST_PASSWORD,APT_SOURCE_DIR,OPENSIM_IAR_PASSWORD,OPENSIM_CONF,OPENSIM_SETUP_END,OPENSIM_SETUP_UI,DEBUG,QUIET

# The global options are the ones before the command; what follows the command is its own (save iar -h URL -v): lib/common reads
# only the first ones
command_args=()
for ((position = 1; position <= $#; position++)); do
	[[ ${!position} != -* ]] || continue
	if [[ ",$COMMANDOPTS," == *",${!position},"* ]]; then
		command_args=("${@:position+1}")
		set -- "${@:1:position}"
	fi
	break
done

# $COMMAND and other runtime values are detected by lib/common
. "$here/../src/lib/common" || die could not source opensim common helpers
set -- "$@" ${command_args[@]+"${command_args[@]}"}

# The version of the command line; with -v, of everything that matters on this machine (the engine tells the rest)
if [[ " $* " == *" --version "* || " $* " == *" -V "* ]]; then
	if [[ "${DEBUG:-}" == yes ]]; then
		printf '%-24s %s\n' w4os-cli "$(cli_version)"
		"$OPENSIM_API" --version -v
	else
		printf 'w4os-cli %s\n' "$(cli_version)"
	fi
	exit 0
fi

if [[ "${1:-}" == --layout ]]; then
	shift
	format=
	while (($#)); do
		case "$1" in
		--format)
			(($# > 1)) || die "--format requires a value"
			format=$2
			shift 2
			;;
		--format=*)
			format=${1#*=}
			shift
			;;
		*) die "unexpected argument for --layout: $1" ;;
		esac
	done
	[[ "$format" == env ]] || die "--layout requires --format=env"
	layout=$(engine GET /layout) || die "could not read the OpenSim system layout"
	layout=$(php -r '
		$layout = json_decode(stream_get_contents(STDIN), true, flags: JSON_THROW_ON_ERROR);
		foreach (["etcRoot", "varRoot", "logsRoot"] as $key) {
			$path = realpath($layout["data"]["attributes"][$key] ?? "");
			if ($path === false) {
				fwrite(STDERR, "Layout path does not exist: " . ($layout["data"]["attributes"][$key] ?? "") . "\n");
				exit(1);
			}
			$layout["data"]["attributes"][$key . "Realpath"] = $path;
		}
		echo json_encode($layout, JSON_THROW_ON_ERROR);
	' <<<"$layout") || die "could not resolve the OpenSim layout paths"
	jq -er '
		.data | select(.type == "layout") | .attributes |
		[
			["currentUser", "CURRENT_USER"],
			["currentUid", "CURRENT_UID"],
			["currentGroup", "CURRENT_GROUP"],
			["currentGid", "CURRENT_GID"],
			["systemUser", "OPENSIM_SYSTEM_USER"],
			["systemUid", "OPENSIM_SYSTEM_UID"],
			["systemGroup", "OPENSIM_SYSTEM_GROUP"],
			["systemGid", "OPENSIM_SYSTEM_GID"],
			["etcRoot", "OPENSIM_ETC_ROOT"],
			["varRoot", "OPENSIM_VAR_ROOT"],
			["logsRoot", "OPENSIM_LOGS_ROOT"],
		    ["etcRootRealpath", "CANONICAL_ETC_ROOT"],
			["varRootRealpath", "CANONICAL_VAR_ROOT"],
			["logsRootRealpath", "CANONICAL_LOGS_ROOT"]
		] as $fields |
		. as $attributes |
		select(all($fields[]; .[0] as $key | $attributes | has($key) and .[$key] != null)) |
		$fields[] as [$key, $variable] |
		"\($variable)=\(.[$key] | tostring | @sh)"
	' <<<"$layout" || die "the OpenSim layout response is incomplete"
	exit 0
fi

system_user=$(run system-user 2>/dev/null)
debug_log system_user $system_user

case ${COMMAND:-} in
'')
	# A word that is no command is an error; no word at all asks for the usage
	(($# == 0)) || die "Unknown command $1."$'\n'"opensim --help"
	help
	end
	;;

setup)
	for argument in "$@"; do
		case "$argument" in
		--prepare | --prepare=*) exec "$libexec/setup" "$@" ;;
		# An install of before the kit: its scenario runs its steps of root here, as the caller (kickstart, as root)
		--legacy) exec "$libexec/setup" "$@" ;;
		esac
	done
	# The package installer creates the system layout as root; setup then runs as the system user.
	run_setup "$@"
	;;

import)
	# The accounts of a list: the list is the caller's, so is the result
	for argument in "$@"; do
		[[ "$argument" != --accounts* ]] || { import_accounts "$@"; exit; }
	done
	# The accounts an import of an install that exists takes: the service made to follow them, as root, by the caller
	accounts=$(install_accounts)
	status=0
	# A migration run by root (sudo) moves the folders of the data of an install another account owns: then what it wrote is given
	# to the accounts of the suite (the system layout of the engine)
	robust= inplace= apply= switch=
	written=()
	for argument in "$@"; do
		[[ "$argument" != --robust* ]] || robust=yes
		[[ "$argument" != --in-place && "$argument" != --forget ]] || inplace=yes
		[[ "$argument" != --apply ]] || apply=yes
		# The grid started by the account of the suite, never root: the switch is done after, as that account
		if [[ "$argument" == --switch ]]; then switch=yes; else written+=("$argument"); fi
	done
	# Its plan too, as the account that will move its data (the plan writes nothing)
	if [[ $(id -u) -eq 0 && -n "$robust" && -z "$inplace" ]] && [[ -n "$apply" || -z "$switch" ]]; then
		"$libexec/import" "${written[@]}" || status=$?
		[[ -z "$apply" ]] || php "$(dirname "$(realpath "$OPENSIM_API")")/opensim-layout.php" >/dev/null || error "could not give what the import wrote to the account of the suite"
		if ((status == 0)) && [[ -n "$switch" ]]; then
			switched=()
			for argument in "${written[@]}"; do [[ "$argument" == --apply || "$argument" == --copy-data ]] || switched+=("$argument"); done
			as_system_user "$libexec/import" "${switched[@]}" --switch || status=$?
		fi
	else
		as_system_user "$libexec/import" "$@" || status=$?
	fi
	# A switch has started the grid: under the account of the service, which it ends by restarting
	restart=
	for argument in "$@"; do [[ "$argument" != --switch ]] || restart=restart; done
	((status == 0)) || restart=
	follow_accounts "$accounts" $restart
	exit "$status"
	;;

region | simulator)
	# What a region is loaded with is a file of the caller's: given to the account of the instances
	as_system_user_with_files "--oar --dump" "$libexec/$COMMAND" "$@"
	;;

oar)
	# The archives are the caller's files
	"$libexec/$COMMAND" "$@"
	;;

web)
	# The install of the engine API (its pool, its listener) writes the configs of the system: as root
	if [[ " $* " == *" --install "* ]]; then
		# Root, or the caller where it may write (OPENSIM_CADDY_ETC...): a folder it may not write in is said
		"$libexec/web" "$@"
	else
		as_system_user "$libexec/web" "$@"
	fi
	;;

install-dotnet)
	log install-dotnet as root
	# The runtime is installed for the whole system: as root, whoever calls
	as_root "$libexec/$COMMAND" "$@"
	;;

module)
	log module as root
	# The modules of the install are in its system config: as root, whoever calls
	as_root "$libexec/$COMMAND" "$@"
	;;

*)
	if [ -e "$libexec/$COMMAND" ]; then
		as_system_user "$libexec/$COMMAND" "$@"
		# as_root "$libexec/$COMMAND" "$@"
	else
		die "Unknown command $COMMAND."$'\n'"opensim --help"
	fi
	;;
esac
