# DOSBox launcher - Print the script content
# USAGE: dosbox_launcher $application
dosbox_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

			# Setup the paths diversion to persistent storage.
			persistent_storage_prerun "$application"

			dosbox_launcher_run "$application"

			# Update persistent storage from current prefix.
			persistent_storage_postrun

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

# DOSBox launcher - Run DOSBox
# USAGE: dosbox_launcher_run $application
dosbox_launcher_run() {
	local application
	application="$1"

	local application_prerun application_postrun dosbox_instructions
	application_prerun=$(application_prerun "$application")
	application_postrun=$(application_postrun "$application")
	dosbox_instructions=$(dosbox_launcher_instructions "$application")

	cat <<- EOF
	# Run the game

	cd "\$PATH_PREFIX"

	$application_prerun

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

	## Silence ShellCheck false-positive
	## Argument mixes string and array. Use * or separate argument.
	# shellcheck disable=SC2145
	"\${PLAYIT_DOSBOX_BINARY:-dosbox}" -c "$dosbox_instructions"

	game_exit_status=\$?
	set -o errexit

	$application_postrun

	EOF
}

# DOSBox launcher - Run commands inside DOSBox
# USAGE: dosbox_launcher_instructions $application
dosbox_launcher_instructions() {
	local application
	application="$1"


	local dosbox_prerun dosbox_postrun
	dosbox_prerun=$(dosbox_prerun "$application")
	dosbox_postrun=$(dosbox_postrun "$application")
	cat <<- EOF
	mount c .
	c:
	EOF
	# If a disk image is required, print the command mounting it
	dosbox_image_mount
	if [ -n "$dosbox_prerun" ]; then
		cat <<- EOF
		$dosbox_prerun
		EOF
	fi
	game_exec_line "$application"
	if [ -n "$dosbox_postrun" ]; then
		cat <<- EOF
		$dosbox_postrun
		EOF
	fi
	cat <<- EOF
	exit
	EOF
}

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

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

