# Set the path to the output directory where packages should be generated.
# This path can then be displayed with path_output_directory.
# USAGE: init_output_directory
init_output_directory() {
	local option_output_dir option_package
	option_output_dir=$(option_value 'output-dir')
	option_package=$(option_value 'package')

	case "$option_package" in
		('gentoo')
			# TODO: "games-playit" should be made configurable, or at least set from a single function/variable.
			PLAYIT_OUTPUT_DIRECTORY="$(realpath --canonicalize-existing "$option_output_dir")/games-playit"
		;;
		(*)
			PLAYIT_OUTPUT_DIRECTORY=$(realpath --canonicalize-existing "$option_output_dir")
		;;
	esac
	export PLAYIT_OUTPUT_DIRECTORY
}

# Set the path to the temporary directory
# This path is exported as $PLAYIT_WORKDIR
# USAGE: init_working_directory
init_working_directory() {
	# Do nothing if PLAYIT_WORKDIR is already set
	if [ -n "${PLAYIT_WORKDIR:-}" ]; then
		return 0
	fi

	# Get the path to the temporary directory
	local temporary_directory_path
	temporary_directory_path=$(option_value 'tmpdir')

	# Generate a directory with a unique name for the current instance
	local game_id
	game_id=$(game_id)
	## "play.it" is used instead of the game identifier if we are too early for a game to be set yet.
	PLAYIT_WORKDIR=$(mktemp --directory --tmpdir="$temporary_directory_path" "${game_id:-play.it}.XXXXX")
	## Ensure that we are always using an absolute path for PLAYIT_WORKDIR,
	## to avoid problems when a relative path has been used with the ./play.it --tmpdir option.
	PLAYIT_WORKDIR=$(realpath "$PLAYIT_WORKDIR")
	export PLAYIT_WORKDIR
}

# Check the validity of the temporary directory
# USAGE: init_working_directory_checks
init_working_directory_checks() {
	# Get the path to the temporary directory
	local temporary_directory_path
	temporary_directory_path=$(option_value 'tmpdir')

	# Check that the given path is valid for temporary files storage
	temporary_directory_checks "$temporary_directory_path"
}

