# 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"
}

