# Mono launcher - Print the script content
# USAGE: mono_launcher $application
mono_launcher() {
	local application
	application="$1"

	local prefix_type
	prefix_type=$(application_prefix_type "$application")
	case "$prefix_type" in
		('symlinks')
			launcher_headers

			# Set the paths that should be available to the generated launcher
			launcher_init_paths "$application"

			# Generate the game prefix
			prefix_symlinks_generate

			# Set up the paths diversion to persistent storage
			## TODO: Only include the snippets used by the current game.
			persistent_storage_initialization
			persistent_storage_common
			persistent_path_diversion
			persistent_storage_update_directories
			persistent_storage_update_files

			mono_launcher_run "$application"

			# Update persistent storage with files from the current prefix
			persistent_storage_update_files_from_prefix

			launcher_exit
		;;
		('none')
			launcher_headers

			# Set the paths that should be available to the generated launcher
			launcher_init_paths "$application"

			mono_launcher_run "$application"
			launcher_exit
		;;
		(*)
			error_launchers_prefix_type_unsupported "$application"
			return 1
		;;
	esac
}

# Mono launcher - Run Mono
# USAGE: mono_launcher_run $application
mono_launcher_run() {
	local application
	application="$1"

	local prefix_type execution_path
	prefix_type=$(application_prefix_type "$application")
	case "$prefix_type" in
		('symlinks')
			execution_path='$PATH_PREFIX'
		;;
		('none')
			execution_path='$PATH_GAME_DATA'
		;;
	esac
	cat <<- EOF
	# Run the game

	cd "$execution_path"

	EOF

	# Set the preload paths for native libraries
	cat <<- 'EOF'
	## Set the preload paths for native libraries
	export LD_LIBRARY_PATH="${PATH_LIBRARIES_USER}:${PATH_LIBRARIES_SYSTEM}:${LD_LIBRARY_PATH:-}"

	EOF

	application_prerun "$application"

	# Apply common workarounds for Mono games
	mono_launcher_tweaks

	cat <<- 'EOF'
	## Do not exit on application failure,
	## to ensure post-run commands are run.
	set +o errexit

	EOF
	game_exec_line "$application"
	cat <<- 'EOF'

	game_exit_status=$?
	set -o errexit

	EOF

	application_postrun "$application"
}

# Mono launcher - Common workarounds
# USAGE: mono_launcher_tweaks
mono_launcher_tweaks() {
	cat <<- 'EOF'
	## Work around terminfo Mono bug,
	## cf. https://github.com/mono/mono/issues/6752
	export TERM="${TERM%-256color}"

	## Work around Mono unpredictable behaviour with non-US locales
	export LANG=C

	EOF
}

# Mono - Print the line starting the game
# USAGE: mono_exec_line $application
# RETURN: the command to execute, including its command line options
mono_exec_line() {
	local application
	application="$1"

	local application_exe application_options
	application_exe=$(application_exe "$application")
	application_options=$(application_options "$application")
	cat <<- EOF
	mono "${application_exe}" $application_options "\$@"
	EOF
}

