# Print the C source of the LD_PRELOAD hack that should be included in the current package
# USAGE: ld_preload_source
ld_preload_source() {
	local ld_preload_source
	ld_preload_source=$(context_value 'LD_PRELOAD_SOURCE')

	# If no value is explictly set, fall back on engine-specific ones
	if [ -z "$ld_preload_source" ]; then
		local game_engine
		game_engine=$(game_engine)
		case "$game_engine" in
			('unity3d')
				ld_preload_source=$(unity3d_disable_map32bit)
			;;
		esac
	fi

	printf '%s' "$ld_preload_source"
}

# Build the .so from the C source of an LD_PRELOAD hack
# USAGE: ld_preload_build $package
ld_preload_build() {
	local package
	package="$1"

	# Set the path to the temporary source snippet
	local path_source
	path_source="${PLAYIT_WORKDIR}/preload-hack.c"

	# Set the path to the packaged .so library
	## TODO: This is used in several places, and should probably by handled by a dedicated function.
	local package_path path_libraries path_binary
	package_path=$(package_path "$package")
	path_libraries=$(path_libraries)
	path_binary="${package_path}${path_libraries}/preload-hack.so"

	# Write the C source snippet
	local ld_preload_source
	ld_preload_source=$(ld_preload_source)
	printf '%s' "$ld_preload_source" > "$path_source"

	# Prepare the compiler options string
	local gcc_options package_architecture
	gcc_options='-shared -Wall -fPIC -ldl'
	package_architecture=$(package_architecture "$package")
	if [ "$package_architecture" = '32' ]; then
		gcc_options="$gcc_options -m32"
	fi

	# Build the .so library
	local binary_directory
	binary_directory=$(dirname "$path_binary")
	mkdir --parents "$binary_directory"
	if ! gcc $gcc_options "$path_source" -o "$path_binary"; then
		error_hack_build_failure
		return 1
	fi

	# Remove the source snippet
	rm "$path_source"
}

