#!/usr/bin/env bash
# opensim simulator add: a simulator made in a grid of this machine with its first region, through the engine (a setup file of one
# simulator).

USAGE='opensim simulator add GRID "SIMULATOR NAME" --region "REGION NAME" [--existing] [--oar FILE | --dump FILE] [--location X,Y] [--size METERS] [--roles ROLE,...] [--http-port PORT] [--owner "AVATAR NAME"] [--estate "ESTATE NAME"] [--db-admin USER] [--apply]
       GRID: the nick of a grid or its name'
HELP="Makes the simulator SIMULATOR NAME in the grid GRID, with its first region REGION NAME. Its database account is the one of the grid, else the one of the environment (OPENSIM_DB_HOST, OPENSIM_DB_USER, OPENSIM_DB_PASS); the database is made when it is missing, by an administrator of the database server (--db-admin USER or OPENSIM_DB_ADMIN_USER, its password from OPENSIM_DB_ADMIN_PASS or asked, never on the command line); its regions join the estate --estate, made when none has that name (by default the estate of --owner, '<Owner> Estate', else the one of the grid), owned by --owner (an account of the grid). What is not given is proposed by the engine: its ports, the nearest free place. --existing takes over the region of that name the grid has already (restored, or moved from another server): its UUID, place, size and owner (the owner of the estate, unless --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; --dump makes the database of the 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): with either, the simulator starts once it is written, and the load is waited for. Without --apply, says what would be written and where, and writes nothing. Otherwise nothing is started: opensim start, once it is written."

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

[[ "${1:-}" == add ]] || die "usage: $USAGE"
shift
words=() region= location= size= roles= http_port= owner= estate= oar= dump= existing= db_admin=${OPENSIM_DB_ADMIN_USER:-} mode=plan
while (($#)); do
	case "$1" in
	--region | --location | --size | --roles | --http-port | --owner | --estate | --db-admin | --oar | --dump)
		(($# > 1)) || die "$1 requires a value"
		key=${1#--}
		printf -v "${key//-/_}" '%s' "$2"
		shift 2
		;;
	--existing) existing=yes; shift ;;
	--apply) mode=apply; shift ;;
	-*) usage_error "unknown option $1" ;;
	*) words+=("$1"); shift ;;
	esac
done
# What is missing named first, then the usage
((${#words[@]} >= 1)) || usage_error "simulator add: GRID is missing"
((${#words[@]} >= 2)) || usage_error "simulator add: the name of the simulator is missing"
((${#words[@]} == 2)) || usage_error "simulator add: one grid and one name of simulator (in quotes when it has spaces), then the options"
[[ -n "$region" ]] || usage_error "simulator add: --region, the name of its first region, is missing"
# The password of the administrator: from the environment, else asked at the terminal, never on the command line
db_admin_password=${OPENSIM_DB_ADMIN_PASS:-}
if [[ -n "$db_admin" && -z "$db_admin_password" && -r /dev/tty ]]; then
	read -rsp "Password of $db_admin on the database server: " db_admin_password </dev/tty
	echo >/dev/tty
fi

setup=$(jq -cn --arg grid "${words[0]}" --arg simulator "${words[1]}" --arg region "$region" --arg location "$location" --arg size "$size" --arg roles "$roles" --arg http_port "$http_port" --arg owner "$owner" --arg estate "$estate" --arg existing "$existing" --arg oar "$oar" --arg dump "$dump" \
	--arg host "${OPENSIM_DB_HOST:-}" --arg user "${OPENSIM_DB_USER:-}" --arg password "${OPENSIM_DB_PASS:-}" \
	--arg admin_user "$db_admin" --arg admin_password "$db_admin_password" \
	'{grid: {nick: $grid}, simulators: [{name: $simulator}
		+ (if $http_port != "" then {http_port: ($http_port | tonumber)} else {} end)
		+ (if $owner != "" or $estate != "" then {estate: ({owner: $owner, name: $estate} | with_entries(select(.value != "")))} else {} end)
		+ {database: ({host: $host, user: $user, password: $password, admin_user: $admin_user, admin_password: $admin_password} | with_entries(select(.value != "")))}
		+ {regions: [{name: $region}
			+ (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)]}]}') || die "--size and --http-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=-)
# What a problem of the plan is said with: the option as typed, its value
plan_option name SIMULATOR "${words[1]}"
plan_option regions.name --region "$region"
plan_option regions.location --location "$location"
plan_option regions.size --size "$size"
plan_option regions.roles --roles "$roles"
plan_option regions.oar --oar "$oar"
plan_option regions.dump --dump "$dump"
plan_option regions.existing --existing
plan_option http_port --http-port "$http_port"
plan_option estate_owner --owner "$owner"
plan_option estate_name --estate "$estate"
setup_file_report "$reply"
