# Build the given LD_PRELOAD hack from its source
# USAGE: hack_build $hack
# RETURN: 0 if everything went well,
#         1 if the build failed
hack_build() {
	local hack
	hack="$1"

	# Write the source file
	local hack_path_source
	hack_path_source=$(hack_path_source "$hack")
	mkdir --parents "${PLAYIT_WORKDIR}/hacks"
	hack_source "$hack" > "$hack_path_source"

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

	# Build the .so library
	local hack_path_library hack_build_status
	hack_path_library=$(hack_path_library "$hack")
	{
		gcc $gcc_options "$hack_path_source" -o "$hack_path_library"
		hack_build_status=$?
	} || true
	if [ "$hack_build_status" -ne 0 ]; then
		error_hack_build_failure
		return 1
	fi
	rm "$hack_path_source"
}

# Print the path of the source file used for building the given hack
# USAGE: hack_path_source $hack
# RETURN: the absolute path to the hack source file
hack_path_source() {
	local hack
	hack="$1"

	local hack_name
	hack_name=$(hack_name "$hack")

	printf '%s/hacks/%s.c' "$PLAYIT_WORKDIR" "$hack_name"
}

# Print the path of the library built for the given hack
# USAGE: hack_path_library $hack
# RETURN: the absolute path to the hack library
hack_path_library() {
	local hack
	hack="$1"

	local hack_name
	hack_name=$(hack_name "$hack")

	printf '%s/hacks/%s.so' "$PLAYIT_WORKDIR" "$hack_name"
}

