# Enable the fake $HOME
# USAGE: fake_home_enable
fake_home_enable() {
	cat <<- 'EOF'
	# Enable the fake $HOME
	HOME_PATH_REAL="$HOME"
	HOME_PATH_FAKE=$(fake_home_path)
	export HOME="$HOME_PATH_FAKE"

	EOF
}

# Disable the fake $HOME
# USAGE: fake_home_disable
fake_home_disable() {
	cat <<- 'EOF'
	# Disable the fake $HOME
	export HOME="$HOME_PATH_REAL"

	EOF
}

# Print the paths relative to the fake $HOME that should be diverted to persistent storage
# USAGE: fake_home_persistent_directories
# RETURN: A list of path to directories,
#         separated by line breaks.
fake_home_persistent_directories() {
	local persistent_directories
	persistent_directories=$(context_value 'FAKE_HOME_PERSISTENT_DIRECTORIES')
	printf '%s' "$persistent_directories"
}

# Handle paths diversion from the fake $HOME to persistent storage
# USAGE: fake_home_persistent
fake_home_persistent() {
	local persistent_directories
	persistent_directories=$(fake_home_persistent_directories)
	{
		cat <<- 'EOF'
		# Divert paths from the fake $HOME to persistent storage

		fake_home_path() {
		    # Fake $HOME path can be explicitely set using an environment variable
		    if [ -n "$PLAYIT_FAKE_HOME_PATH" ]; then
		        printf '%s' "$PLAYIT_FAKE_HOME_PATH"
		        return 0
		    fi
		    # Compute the default fake $HOME path if none has been explicitely set
		    printf '%s/play.it/home/%s' \
		        "${XDG_CACHE_HOME:="$HOME/.cache"}" \
		        "$GAME_ID"
		}
		FAKE_HOME_PATH=$(fake_home_path)

		## Divert paths set by the XDG Base Directory Specification
		## cf. https://specifications.freedesktop.org/basedir-spec/basedir-spec-0.8.html
		while read -r xdg_path_absolute; do
		    if printf '%s' "$xdg_path_absolute" | grep --quiet --regexp="^${HOME}/"; then
		        xdg_path_relative=$(printf '%s' "$xdg_path_absolute" | sed "s#^${HOME}/##")
		        persistent_path_diversion "$FAKE_HOME_PATH" "$HOME" "$xdg_path_relative"
		    fi
		done << EOL
		${XDG_CACHE_HOME:-${HOME}/.cache}
		${XDG_CONFIG_HOME:-${HOME}/.config}
		${XDG_DATA_HOME:-${HOME}/.local/share}
		${XDG_STATE_HOME:-${HOME}/.local/state}
		EOL
		unset xdg_path_absolute

		EOF
	} | sed --regexp-extended 's/( ){4}/\t/g'
	cat <<- EOF
	## Divert paths specific to the current game
	FAKE_HOME_PERSISTENT_DIRECTORIES="$persistent_directories"
	EOF
	{
		cat <<- 'EOF'
		while read -r directory; do
		    if [ -z "$directory" ]; then
		        continue
		    fi
		    persistent_path_diversion "$FAKE_HOME_PATH" "${USER_PERSISTENT_PATH}/fake-home" "$directory"
		done << EOL
		$(printf '%s' "$FAKE_HOME_PERSISTENT_DIRECTORIES")
		EOL
		unset directory

		EOF
	} | sed --regexp-extended 's/( ){4}/\t/g'
}

