# Build and include all PRELOAD hacks
# USAGE: hacks_inclusion_default
# RETURN: 0 if all hacks could be built and included in the packages,
#         0 if no hacks are to be included,
#         1 otherwise
hacks_inclusion_default() {
	local packages_list package hacks_list hack
	packages_list=$(packages_list)
	for package in $packages_list; do
		hacks_list=$(hacks_included_in_package "$package")
		if [ -z "$hacks_list" ]; then
			continue
		fi
		for hack in $hacks_list; do
			hack_build "$hack"
			(
				set_current_package "$package"
				hack_inclusion "$hack"
			)
		done
	done
}

# Include the hack library for the given hack into its target package
# USAGE: hack_inclusion $hack
# RETURN: 0 if the inclusion succeeded,
#         1 if the library could not be found
hack_inclusion() {
	local hack
	hack="$1"

	local hack_path_library
	hack_path_library=$(hack_path_library "$hack")
	if [ ! -f "$hack_path_library" ]; then
		# TODO: Display an explicit error message
		return 1
	fi

	local hack_package hack_package_path path_libraries
	hack_package=$(hack_package "$hack")
	hack_package_path=$(package_path "$hack_package")
	path_libraries=$(path_libraries)
	install -D --mode=644 --target-directory="${hack_package_path}${path_libraries}/preload-hacks" "$hack_path_library"
	rm "$hack_path_library"
}

# Print the pre-run actions required to use the given hack
# USAGE: hack_application_prerun $hack
# RETURN: the pre-run actions, as a string spanning multiple lines
hack_application_prerun() {
	local hack
	hack="$1"

	local hack_description hack_description_line
	hack_description=$(hack_description "$hack")
	while read -r hack_description_line; do
		cat <<- EOF
		# $hack_description_line
		EOF
	done <<- EOL
	$(printf '%s' "$hack_description")
	EOL

	local hack_name path_libraries
	hack_name=$(hack_name "$hack")
	path_libraries=$(path_libraries)
	cat <<- EOF
	export LD_PRELOAD="\${LD_PRELOAD}:${path_libraries}/preload-hacks/${hack_name}.so"
	EOF
}

# Print the list of hacks included in the given package
# USAGE: hacks_included_in_package $package
# RETURN: a list of hack identifiers, one per line
#         or an empty string if no hack is included in the current package
hacks_included_in_package() {
	local package
	package="$1"

	local hacks_list hack hack_package
	hacks_list=$(hacks_list)
	for hack in $hacks_list; do
		hack_package=$(hack_package "$hack")
		if [ "$hack_package" = "$package" ]; then
			printf '%s\n' "$hack"
		fi
	done
}

