#!/usr/bin/env bash
# opensim region: a region given to a simulator of a grid of this machine (add), or its roles and its owner changed (set), through the
# engine.

USAGE="opensim region add GRID SIMULATOR --name NAME [--existing] [--oar FILE | --dump FILE] [--location X,Y] [--size METERS] [--roles ROLE,...] [--port PORT] [--apply]
       opensim region set GRID REGION [--roles ROLE,...] [--owner UUID]
       opensim region remove GRID REGION [--apply]"
HELP="add gives a region to the simulator SIMULATOR of the grid GRID (made when the grid has no simulator of that name). What is not given is proposed by the engine: the nearest free place, the next port. --existing takes over the region of that name the grid has already (restored, or moved from another server): its UUID, place, size and owner are the ones the grid keeps, and it is refused while the simulator that runs it elsewhere answers. --oar loads an archive of the region (OAR) into it once it runs: the simulator starts (or loads the region) and the load is waited for. --dump makes the database of a new simulator from the dump of the database of the simulator the region comes from (a .sql or .sql.gz, of opensim backup or of mysqldump), before it starts: the region keeps all it had there. --size is a multiple of 256 meters; --roles are DefaultRegion, DefaultHGRegion, FallbackRegion... Without --apply, says what would be written and where, and writes nothing.
set gives the region REGION (its name or its UUID) these roles and only them (--roles \"\" takes them all away), or another owner (--owner, the UUID of an avatar: the owner of its estate). Its name, its place and its size are changed in its file.
remove takes the region REGION out of its simulator of this machine, stopped, so that another simulator can be given it (add --existing): its file set aside as FILE.removed (named back, the region is back), or its section taken out of a file that describes other regions. What it holds stays in the database of that simulator. Without --apply, says what would be done."

source "$(dirname "$(realpath "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")/../src/lib/common"

# set: the roles and the owner of a region, by the PATCH of the engine
if [[ "${1:-}" == set ]]; then
	shift
	words=() given=()
	declare -A value=()
	while (($#)); do
		case "$1" in
		--roles | --owner)
			(($# > 1)) || die "$1 requires a value"
			value[${1#--}]=$2 given+=("${1#--}")
			shift 2
			;;
		--roles=* | --owner=*)
			key=${1%%=*} key=${key#--}
			value[$key]=${1#*=} given+=("$key")
			shift
			;;
		-*) die "unknown option $1 (usage: $USAGE)" ;;
		*) words+=("$1"); shift ;;
		esac
	done
	((${#words[@]} == 2 && ${#given[@]} > 0)) || die "usage: $USAGE"
	attributes=$(jq -cn --arg roles "${value[roles]-}" --arg owner "${value[owner]-}" --arg given "${given[*]}" '
		($given | split(" ")) as $asked
		| (if ($asked | index("roles")) then {roles: ($roles | split(",") | map(select(. != "")))} else {} end)
		+ (if ($asked | index("owner")) then {owner: $owner} else {} end)')
	path="/grids/$(jq -rn --arg v "${words[0]}" '$v | @uri')/regions/$(jq -rn --arg v "${words[1]}" '$v | @uri')"
	reply=$(jq -cn --argjson attributes "$attributes" '{data: {type: "regions", attributes: $attributes}}' | engine PATCH "$path" --data=-) || true
	jq -e '.data.attributes' <<<"$reply" >/dev/null 2>&1 ||
		die "$(jq -r 'if .detail then .detail else (.title // "the engine did not answer") end' <<<"$reply" 2>/dev/null || printf '%s' "$reply")"
	jq -r '.data.attributes as $a
		| "\($a.name): \(if ($a.roles | length) > 0 then ($a.roles | join(", ")) else "no role" end); owner \($a.ownerName // $a.owner // "nobody")",
		(if (.meta.reminders // []) | length > 0 then "Then:", (.meta.reminders[] | "  \(if type == "object" then .detail else . end)") else empty end)' <<<"$reply"
	exit 0
fi

# remove: the region taken out of its simulator, by the DELETE of the engine
if [[ "${1:-}" == remove ]]; then
	shift
	words=() mode=plan
	while (($#)); do
		case "$1" in
		--apply) mode=apply; shift ;;
		-*) die "unknown option $1 (usage: $USAGE)" ;;
		*) words+=("$1"); shift ;;
		esac
	done
	((${#words[@]} == 2)) || die "usage: $USAGE"
	path="/grids/$(jq -rn --arg v "${words[0]}" '$v | @uri')/regions/$(jq -rn --arg v "${words[1]}" '$v | @uri')"
	reply=$(engine GET "$path" </dev/null) || true
	jq -e '.data.attributes' <<<"$reply" >/dev/null 2>&1 ||
		die "$(jq -r 'if .detail then .detail else (.title // "the engine did not answer") end' <<<"$reply" 2>/dev/null || printf '%s' "$reply")"
	jq -e '.data.attributes.file // "" | length > 0' <<<"$reply" >/dev/null || die "${words[1]}: no simulator of this machine describes it"
	if [[ "$mode" != apply ]]; then
		jq -r '.data.attributes | "Would take \(.name) out of the simulator \(.simulator) (\(.file)); what it holds stays in its database.", "Nothing was changed: add --apply to do it."' <<<"$reply"
		exit 0
	fi
	reply=$(engine DELETE "$path" </dev/null) || true
	if [[ -n "$reply" ]] && ! jq -e '.meta' <<<"$reply" >/dev/null 2>&1; then
		die "$(jq -r 'if .detail then .detail else (.title // "the engine did not answer") end' <<<"$reply" 2>/dev/null || printf '%s' "$reply")"
	fi
	say "${words[1]}: taken out of its simulator"
	jq -r '(.meta.reminders // [])[] | "- \(if type == "object" then .detail else . end)"' <<<"${reply:-{\}}"
	exit 0
fi

[[ "${1:-}" == add ]] || die "usage: $USAGE"
shift
words=() name= location= size= roles= port= existing= oar= dump= mode=plan
while (($#)); do
	case "$1" in
	--name | --location | --size | --roles | --port | --oar | --dump)
		(($# > 1)) || die "$1 requires a value"
		printf -v "${1#--}" '%s' "$2"
		shift 2
		;;
	--name=* | --location=* | --size=* | --roles=* | --port=* | --oar=* | --dump=*)
		key=${1%%=*}
		printf -v "${key#--}" '%s' "${1#*=}"
		shift
		;;
	--existing) existing=yes; shift ;;
	--apply) mode=apply; shift ;;
	-*) die "unknown option $1 (usage: $USAGE)" ;;
	*) words+=("$1"); shift ;;
	esac
done
((${#words[@]} == 2)) && [[ -n "$name" ]] || die "usage: $USAGE"

setup=$(jq -cn --arg grid "${words[0]}" --arg simulator "${words[1]}" --arg name "$name" --arg location "$location" --arg size "$size" --arg roles "$roles" --arg port "$port" --arg existing "$existing" --arg oar "$oar" --arg dump "$dump" \
	'{grid: {nick: $grid}, simulators: [{name: $simulator, regions: [{name: $name}
		+ (if $existing != "" then {existing: true} else {} end)
		+ (if $oar != "" then {oar: $oar} else {} end)
		+ (if $dump != "" then {dump: $dump} else {} end)
		+ (if $location != "" then {location: $location} else {} end)
		+ (if $size != "" then {size: ($size | tonumber)} else {} end)
		+ (if $roles != "" then {roles: ($roles | split(","))} else {} end)
		+ (if $port != "" then {port: ($port | tonumber)} else {} end)]}]}') || die "--size and --port are numbers"
reply=$(jq -cn --argjson setup "$setup" --arg mode "$mode" '{data: {type: "files", attributes: {setup: $setup, mode: $mode}}}' | setup_file_engine POST /setups/files --data=-)
setup_file_report "$reply"
