#!/usr/bin/env bash
# opensim import: brings what another install has into this one, through the engine (POST /setups/imports). A simulator of an older
# install joins a grid of this machine, or the settings of an older grid come into the OpenSim.ini of a grid of this machine: planned,
# written with --apply only.

USAGE='opensim import FILE [--apply]
       opensim import --simulator FILE [--simulator FILE...] GRID [--name "SIMULATOR NAME"] [--core DIR] [--no-scripts] [--apply]
       opensim import --grid-settings FILE GRID [--apply]
       opensim import --accounts FILE GRID [--format csv|json|yaml] [--keep-going] [--create-groups] [--result FILE] [--apply]
       opensim import --accounts FILE --robust FILE [--format csv|json|yaml] [--keep-going] [--create-groups] [--result FILE] [--apply]
       opensim import --robust FILE [--nick NICK] [--grid-name "GRID NAME"] [--site URL] [--core DIR] [--simulator FILE...] [--copy-data] [--apply] [--switch]
       opensim import --robust FILE --in-place [--nick NICK] [--core DIR] [--simulator FILE...] [--name "SIMULATOR NAME"] [--apply]
       opensim import --robust FILE --forget [--apply]
       GRID: the nick of a grid or its name'
HELP="Applies a setup file (JSON or YAML: the simulators of a grid of this machine, their regions with name, location, size, roles) to the grid it names, or brings a simulator of another install (its OpenSim.ini, or its file of opensim.d, and the regions it names) into the grid GRID of this machine. Its database is kept as it is (the same one, nothing is copied), its regions are copied with their UUID and their place, its ports and its own settings are kept. Without --apply, says what would be written and where, and writes nothing.
  FILE              a setup file: its simulators are made, or given its regions when the grid has them
  --simulator FILE  the config of a simulator of another install; several, planned together and checked between them (ports,
                    region names and UUIDs, places of the map), written in their order
  --name NAME       its name in the grid, when it is not the one of its config (one simulator only)
  --core DIR        the core it runs with, when it is not the one of the grid (one simulator only)
  --no-scripts      do not copy the state of its scripts (every script starts again from the beginning)
  --grid-settings FILE
                    the OpenSim.ini of a grid of another install: the settings of its options (search, economy and Gloebit,
                    offline messages, profiles, groups), with the files it includes, come into the OpenSim.ini of GRID, where
                    the repair of the options finds them for its simulators; what GRID says already is kept, a secret is masked
  --accounts FILE   a list of accounts to make in GRID: CSV (first, last, email, password, with or without a header line), JSON
                    or YAML (a list of objects with the same keys); the names GRID has are skipped, an account given no
                    password gets one, kept in the result file (mode 600, accounts-result-<date>.csv or --result FILE), never
                    shown; the first failure stops the others, unless --keep-going; --robust ROBUST_INI instead of GRID
                    makes them in a grid this install does not manage, by its Robust config where it is (nothing registered);
                    groups: each account, the ones that exist too, joins its groups (Group or Group:Role, | between them in
                    CSV), nothing taken away; a missing group or role is an error, made with --create-groups (the owner of
                    the grid founding a group, a role with the powers of Everyone)
  --robust FILE     the Robust config of a grid of another install (Robust.HG.ini, Robust.ini), migrated into this one: the
                    same grid (its database kept as it is, so its accounts and its regions), its config made here with its own
                    settings kept; --simulator brings its simulators in the same run, --nick and --core when they are not the
                    ones of its config and of this install. The folders of its data in the old install (its assets, its map
                    tiles...) are moved into the layout of this one, each named in the plan (never measured first); run as root
                    when the old install is another account's
  --grid-name NAME  the name of the migrated grid, ASCII (its grid info sends no other characters): instead of the one of its
                    config made ASCII
  --site URL        the address of its Quick Start website, kept with the grid (opensim web GRID site --install puts it there)
  --copy-data       copy the folders of its data instead of moving them: the old install is left whole
  --in-place        the grid of another install run where it is, not migrated: only its section of the config of the suite
                    ([Grid <nick>]: its Robust config, its core, its simulators) is written, disabled; the install is never
                    changed; --name names its simulator (one), --forget removes the section
  --switch          once the old Robust is stopped: the grid and its simulators enabled and started here (with --apply, or
                    after it)
  --apply           write it (disabled: stop the old one, then opensim enable and opensim start the new one)"

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

files=() grid= name= core= mode=plan scripts=true settings= accounts= format= keep=false creategroups=false robust= nick= gridname= site= switch=false inplace=false forget=false copydata=false
while (($#)); do
	case "$1" in
	--accounts)
		(($# > 1)) || die "--accounts requires the list of the accounts"
		accounts=$2
		shift 2
		;;
	--accounts=*) accounts=${1#*=}; shift ;;
	--format)
		(($# > 1)) || die "--format requires csv, json or yaml"
		format=$2
		shift 2
		;;
	--format=*) format=${1#*=}; shift ;;
	--keep-going) keep=true; shift ;;
	--create-groups) creategroups=true; shift ;;
	--robust)
		(($# > 1)) || die "--robust requires the Robust config of the other install"
		robust=$2
		shift 2
		;;
	--robust=*) robust=${1#*=}; shift ;;
	--nick)
		(($# > 1)) || die "--nick requires a nick"
		nick=$2
		shift 2
		;;
	--nick=*) nick=${1#*=}; shift ;;
	--grid-name)
		(($# > 1)) || die "--grid-name requires a name"
		gridname=$2
		shift 2
		;;
	--grid-name=*) gridname=${1#*=}; shift ;;
	--site)
		(($# > 1)) || die "--site requires the address of the website"
		site=$2
		shift 2
		;;
	--site=*) site=${1#*=}; shift ;;
	--switch) switch=true; shift ;;
	--copy-data) copydata=true; shift ;;
	--in-place) inplace=true; shift ;;
	--forget) forget=true; shift ;;
	--simulator)
		(($# > 1)) || die "--simulator requires the config of the simulator"
		files+=("$2")
		shift 2
		;;
	--simulator=*) files+=("${1#*=}"); shift ;;
	--grid-settings)
		(($# > 1)) || die "--grid-settings requires the OpenSim.ini of the other grid"
		settings=$2
		shift 2
		;;
	--grid-settings=*) settings=${1#*=}; shift ;;
	--name)
		(($# > 1)) || die "--name requires a name"
		name=$2
		shift 2
		;;
	--name=*) name=${1#*=}; shift ;;
	--core)
		(($# > 1)) || die "--core requires a folder"
		core=$2
		shift 2
		;;
	--core=*) core=${1#*=}; shift ;;
	--apply) mode=apply; shift ;;
	--no-scripts) scripts=false; shift ;;
	-*) usage_error "unknown option $1" ;;
	*)
		[[ -z "$grid" ]] || usage_error "one grid only"
		grid=$1
		shift
		;;
	esac
done
# A grid of another install, migrated: the same grid, its config made here, its simulators with it; switched once the old one is stopped
# A grid of another install, run where it is: its section of the config of the suite planned, written, or removed
if [[ -n "$robust" && -z "$accounts" ]] && [[ "$inplace" == true || "$forget" == true ]]; then
	[[ -z "$grid$settings" ]] && { ((${#files[@]} <= 1)) || [[ -z "$name" ]]; } || die "usage: $USAGE"
	[[ -r "$robust" ]] || die "cannot read $robust"
	paths=()
	for file in ${files[@]+"${files[@]}"}; do
		[[ -r "$file" ]] || die "cannot read $file"
		paths+=("$(realpath "$file")")
	done
	request=$(jq -cn --arg file "$(realpath "$robust")" --arg nick "$nick" --arg core "$core" --arg name "$name" --arg mode "$mode" --argjson forget "$forget" \
		'{data: {type: "imports", attributes: ({kind: "robust", file: $file, mode: $mode, inPlace: true, forget: $forget, simulators: ($ARGS.positional | map({file: .} + (if $name != "" then {name: $name} else {} end)))} + ({nick: $nick, core: $core} | with_entries(select(.value != ""))))}}' \
		--args ${paths[@]+"${paths[@]}"})
	reply=$(engine POST /setups/imports --data=- <<<"$request") || 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 |
		"Grid \(.grid) in place: [Grid \(.grid)] of \(.config)",
		((.section // {}) | to_entries[] | "  \(.key) = \(.value)"),
		"",
		(if .forget then (if .applied then "Forgotten: the section is removed, the install is as it was." else "Nothing was removed: add --apply to forget it." end)
		 elif .applied then "Written: the section of the grid" + (if ((.accounts // {}) | length) > 0 then ", and the accounts of the install" else "" end) + (if ((.gridInfo // []) | length) > 0 then "; of the install, only its grid info made ASCII." else "; nothing of the install." end) else "Nothing written.\n\(env.OPENSIM_AGAIN // "Add") --apply" end),
		((.accounts // {}) | to_entries[] | "  \(.key): \(if .value.from == "" then "(none)" else .value.from end) -> \(.value.to)"),
		(if ((.gridInfo // []) | length) > 0 then "Grid info made ASCII in the install" + (if .applied then "" else " (with --apply)" end) + ":", ((.gridInfo // [])[] | "  \(.)") else empty end),
		# Once applied, the service is made to follow the accounts by the caller (follow_accounts)
		(.applied as $applied | (.reminders // [])[] | select(.code != "install-account" or ($applied | not)) | "- \(.detail | gsub("\n"; "\n  "))")' <<<"$reply"
	exit
fi
if [[ -n "$robust" && -z "$accounts" ]]; then
	[[ -z "$grid$settings$name" ]] || die "usage: $USAGE"
	[[ -r "$robust" ]] || die "cannot read $robust"
	paths=()
	for file in ${files[@]+"${files[@]}"}; do
		[[ -r "$file" ]] || die "cannot read $file"
		paths+=("$(realpath "$file")")
	done
	request=$(jq -cn --arg file "$(realpath "$robust")" --arg nick "$nick" --arg gridname "$gridname" --arg site "$site" --arg core "$core" --arg mode "$mode" --argjson switch "$switch" --argjson scripts "$scripts" --argjson copydata "$copydata" \
		'{data: {type: "imports", attributes: ({kind: "robust", file: $file, mode: $mode, switch: $switch, copyData: $copydata, simulators: ($ARGS.positional | map({file: .} + (if $scripts then {} else {scripts: false} end)))} + ({nick: $nick, gridName: $gridname, site: $site, core: $core} | with_entries(select(.value != ""))))}}' \
		--args ${paths[@]+"${paths[@]}"})
	reply=$(engine POST /setups/imports --data=- <<<"$request") || 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")"
	# A plan with problems: the problems alone, an error; nothing to write is shown, nothing to apply is proposed
	index=0
	for file in ${paths[@]+"${paths[@]}"}; do
		plan_option "simulators.$index" --simulator "$file"
		index=$((index + 1))
	done
	if plan_has_problems "$reply"; then
		error "$(plan_problems "$reply")"
		exit 1
	fi
	jq -r --argjson switching "$switch" '
		def said: (if type == "object" then .detail else . end) | gsub("\n"; "\n  ");
		.data.attributes |
		# A switch alone (written before): what it did, not the plan of the writing
		if .switched and (.applied | not) then
			"Grid \(.name) (\(.grid)), from \(.source): switched, enabled" + (if ((.failed // {}) | length) > 0 or ((.starting // []) | length) > 0 then ", NOT all started" else " and started here" end),
			(if (.started | length) > 0 then "Started: \(.started | join(", "))" else empty end),
			((.starting // [])[] | "Still starting, not answering yet: \(.) (opensim status, its log)"),
			((.failed // {}) | to_entries[] | "Not started: \(.key): \(.value)")
		else
		"Grid \(.name) (\(.grid)), from \(.source)",
		"Config:   \(.config)",
		"Database: \(.database.name) @ \(.database.host) (user \(.database.user)), kept as it is",
		"Ports:    public \(.ports.public), private \(.ports.private)" + (if .ports.console then ", console \(.ports.console)" else "" end),
		(if ((.gridInfo // []) | length) > 0 then "Grid info made ASCII:", ((.gridInfo // [])[] | "  \(.)") else empty end),
		"Settings kept: \(.settings | length)",
		((.settings // [])[] | "  [\(.section)] \(.key) = \(.value)"),
		"Settings left: \((.dropped // []) | length)" + (if ((.dropped // []) | length) > 0 then " (" + (.dropped | group_by(.reason) | map("\(.[0].reason) \(length)") | join(", ")) + ")" else "" end),
		(if .backup then "Backup of the source first: \(.backup.file) (databases \(.backup.databases | join(", ")))" else empty end),
		(if ((.backup.remote // []) | length) > 0 then "  Not in it, of another server (its own backups keep them): \(.backup.remote | join(", "))" else empty end),
		(if ((.simulators.steps // []) | length) > 0 then "Simulators: " + (.simulators.steps | map("\(.simulator) (\(.slug))") | join(", ")) else empty end),
		(if ((.data // []) | length) > 0 then "Data " + (if .data[0].mode == "copy" then "copied" else "moved" end) + " into this install (not measured first):", (.data[] | "  \(.from) -> \(.to)" + (if .acrossFilesystems then " (across file systems: the move tool copies it)" else "" end)) else empty end),
		"",
		(if .applied then "Written:" else "Would write:" end),
		((.writes // [])[] | "  \(.)"),
		(if .applied then "Report:   \(.report)" elif .switched then empty else "Nothing written.\n\(env.OPENSIM_AGAIN // "Add") --apply" end),
		((.accounts // {}) | to_entries[] | "Account:  \(.key) \(if .value.from == "" then "(none)" else .value.from end) -> \(.value.to) (the owner of the old install, whose data stays where it is)"),
		(if .switched then (if (.started | length) > 0 then "Started: \(.started | join(", "))" else empty end), ((.starting // [])[] | "Still starting, not answering yet: \(.) (opensim status, its log)"), ((.failed // {}) | to_entries[] | "Not started: \(.key): \(.value)") else (.applied as $applied | (.reminders // [])[] | select(type != "object" or .code != "install-account" or ($applied | not)) | select(($switching | not) or type != "object" or (.code != "import-stop-grid" and .code != "import-switch")) | "- \(said)") end)
		end' <<<"$reply"
	# Nothing to write, or an instance the switch did not start: an error
	jq -e '((.data.attributes.problems // {}) | length == 0) and ((.data.attributes.failed // {}) | length == 0) and ((.data.attributes.starting // []) | length == 0)' <<<"$reply" >/dev/null
	exit
fi
# The accounts of a list (- : from the standard input, as the command line sends the file of its caller): what is done on the error
# output, the result (with the passwords made here) on the standard output once applied, for the caller to keep
if [[ -n "$accounts" ]]; then
	[[ -n "$grid" || -n "$robust" ]] && [[ -z "$grid" || -z "$robust" ]] && ((${#files[@]} == 0)) && [[ -z "$settings" ]] || die "usage: $USAGE"
	[[ -z "$robust" || -r "$robust" ]] || die "cannot read $robust"
	if [[ "$accounts" == - ]]; then
		text=$(cat)
	else
		[[ -r "$accounts" ]] || die "cannot read $accounts"
		text=$(<"$accounts")
	fi
	request=$(jq -cn --arg text "$text" --arg grid "$grid" --arg robust "${robust:+$(realpath "$robust")}" --arg mode "$mode" --arg format "$format" --argjson keep "$keep" --argjson creategroups "$creategroups" \
		'{data: {type: "imports", attributes: ({kind: "accounts", text: $text, mode: $mode, keepGoing: $keep, createGroups: $creategroups} + (if $robust != "" then {robust: $robust} else {grid: $grid} end) + (if $format != "" then {format: $format} else {} end))}}')
	reply=$(engine POST /setups/imports --data=- <<<"$request") || 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 |
		(.errors[] | "import: \(.)"),
		(.results[] | ((if (.line // 0) > 0 then "line \(.line): " else "" end) + "\(.status)\(" " * (14 - (.status | length))) \(.first) \(.last)" + (if .detail != "" then " (\(.detail))" else "" end)),
			((.groups // [])[] | "    \(.status)\(" " * (11 - (.status | length))) \(.group)" + (if .role then ":\(.role)" else "" end) + (if .detail != "" then " (\(.detail))" else "" end))),
		"",
		(.counts | to_entries | map("\(.value) \(.key)") | join(", ")),
		(if .applied then empty else "Nothing written.\n\(env.OPENSIM_AGAIN // "Add") --apply" end)' <<<"$reply" >&2
	jq -r '.data.attributes.csv // empty' <<<"$reply"
	# A line that cannot be used, an account that failed or was not tried: an error
	jq -e '.data.attributes | (.errors | length) == 0 and ((.counts.failed // 0) + (.counts["not tried"] // 0)) == 0' <<<"$reply" >/dev/null
	exit
fi
# The settings of a grid of another install, into the OpenSim.ini of a grid of this machine
if [[ -n "$settings" ]]; then
	[[ -n "$grid" ]] && ((${#files[@]} == 0)) || die "usage: $USAGE"
	[[ -r "$settings" ]] || die "cannot read $settings"
	request=$(jq -cn --arg file "$(realpath "$settings")" --arg grid "$grid" --arg mode "$mode" '{data: {type: "imports", attributes: {kind: "grid-settings", file: $file, grid: $grid, mode: $mode}}}')
	reply=$(engine POST /setups/imports --data=- <<<"$request") || 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")"
	# The plan, or what was written: the values as the engine says them, a secret masked
	jq -r '.data.attributes |
		"Settings of the grid \(.grid), from \(.source)",
		(if ((.files // {}) | length) == 0 then "Nothing to bring: the grid has them already." else ((.files // {}) | to_entries[] | "Into \(.key):", (.value | to_entries[] | .key as $section | .value | to_entries[] | "  [\($section)] \(.key) = \(.value)")) end),
		(.notes[] | "- \(.)"),
		"",
		(if .applied then "Written to \((.files // {}) | keys | join(", "))", "Then the repair of the options lays them in its simulators (at the next upgrade of the packages, or now: opensim api POST /grids/\(.grid)/options/repair mode=apply)" elif ((.files // {}) | length) > 0 then "Nothing written.\n\(env.OPENSIM_AGAIN // "Add") --apply" else empty end)' <<<"$reply"
	exit
fi
# A setup file: the one word given, without --simulator
if ((${#files[@]} == 0)); then
	[[ -n "$grid" && -r "$grid" ]] || die "usage: $USAGE"
	setup_file "$grid" "$mode"
	exit
fi
[[ -n "$grid" ]] || die "usage: $USAGE"
((${#files[@]} == 1)) || [[ -z "$name$core" ]] || usage_error "--name and --core are for one simulator"
paths=()
for file in "${files[@]}"; do
	[[ -r "$file" ]] || die "cannot read $file"
	paths+=("$(realpath "$file")")
done

if ((${#paths[@]} == 1)); then
	request=$(jq -cn --arg file "${paths[0]}" --arg grid "$grid" --arg name "$name" --arg core "$core" --arg mode "$mode" --argjson scripts "$scripts" \
		'{data: {type: "imports", attributes: ({kind: "simulator", file: $file, grid: $grid, mode: $mode} + ({name: $name, core: $core} | with_entries(select(.value != ""))) + (if $scripts then {} else {scripts: false} end))}}')
else
	request=$(jq -cn --arg grid "$grid" --arg mode "$mode" --argjson scripts "$scripts" '{data: {type: "imports", attributes: {kind: "simulator", grid: $grid, mode: $mode, simulators: ($ARGS.positional | map({file: .} + (if $scripts then {} else {scripts: false} end)))}}}' --args "${paths[@]}")
fi
reply=$(engine POST /setups/imports --data=- <<<"$request") || 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")"

# A plan with problems: the problems alone, an error; nothing to write is shown, nothing to apply is proposed
index=0
for file in ${paths[@]+"${paths[@]}"}; do
	plan_option "simulators.$index" --simulator "$file"
	index=$((index + 1))
done
if plan_has_problems "$reply"; then
	error "$(plan_problems "$reply")"
	exit 1
fi
# The plan, or what was written: what the engine says, as lines (several simulators: each, then what is wrong between them)
jq -r '
	def said: (if type == "object" then .detail else . end) | gsub("\n"; "\n  ");
	def step:
		"Simulator \(.simulator) (\(.slug)) of the grid \(.grid), from \(.source)",
		"Config:   \(.config)",
		"Database: \(.database.name) @ \(.database.host) (user \(.database.user)), kept as it is",
		"Ports:    http \(.ports.http)" + (if .ports.console then ", console \(.ports.console)" else "" end),
		"Regions:  \(.regions | length)",
		(.regions[] | "  \(.name) (\(.uuid), \(.location)): \(.file) -> \(.to)"),
		(if .backup then "Backup of the source first: \(.backup.file) (databases \(.backup.databases | join(", ")), \(.backup.files | length) files)" else empty end),
		(if ((.backup.remote // []) | length) > 0 then "  Not in it, of another server (its own backups keep them): \(.backup.remote | join(", "))" else empty end),
		(if .scripts then (if .scripts.copied then "State of the scripts: \(.scripts.from | join(", ")) -> \(.scripts.to) (\(.scripts.size) bytes)" elif (.scripts.from | length) > 0 then "State of the scripts: not copied, every script starts again" else empty end) else empty end),
		"Settings kept: \(.settings | length)",
		(if .dropped then "Settings left: \(.dropped | length)" + (if (.dropped | length) > 0 then " (" + (.dropped | group_by(.reason) | map("\(.[0].reason) \(length)") | join(", ")) + ")" else "" end) else empty end),
		((.dropped // [])[] | select(.reason == "replaced") | "  [\(.section)] \(.key) = \(.value)" + (if .replacement then " -> \(.replacement)" else ": written by the new config its own way" end));
	.data.attributes |
	if .steps then
		(.steps[] | step, ""),
		(if .applied then "Written:" else "Would write:" end),
		(.writes[] | "  \(.)"),
		"",
		(if .applied then empty else "Nothing written.\n\(env.OPENSIM_AGAIN // "Add") --apply" end),
		(.reminders[] | "- \(said)")
	else
		step,
		(if .applied then "Written:" else "Would write:" end),
		(.writes[] | "  \(.)"),
		"",
		(if .applied then "Report:   \(.report)" else "Nothing written.\n\(env.OPENSIM_AGAIN // "Add") --apply" end),
		(.reminders[] | "- \(said)")
	end' <<<"$reply"
# Several simulators that cannot be written together end in an error
jq -e '(.data.attributes.problems // {}) | length == 0' <<<"$reply" >/dev/null
