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

	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

	## 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 "$PATH_FAKE_HOME" "$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
	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 "$PATH_FAKE_HOME" "${PATH_PERSISTENT}/fake-home" "$directory"
	done << EOL
	$(printf '%s' "$FAKE_HOME_PERSISTENT_DIRECTORIES")
	EOL
	unset directory

	EOF
}

