#!/usr/bin/env sh

# This script replaces the occurrences of @rpath/ with the content of $(pwd)
# in all dylib occurrences in the directory in which the script is being run.

DIR=$(pwd)

echo "${DIR}"

replace_id () {
	local NEW_ID="$1"
	local DYLIB="$2"

	echo "'${NEW_ID}' for '${DYLIB}'"

	echo install_name_tool -id "${NEW_ID}" "${DYLIB}"
	install_name_tool -id "${NEW_ID}" "${DYLIB}"
}

replace_rpath () {
	local OLD_PATH="$1"
	local NEW_PATH="$2"
	local DYLIB="$3"

	echo "'${OLD_PATH}' -> '${NEW_PATH}' in '${DYLIB}'"

	echo install_name_tool -change "${OLD_PATH}" "${NEW_PATH}" "${DYLIB}"
	install_name_tool -change "${OLD_PATH}" "${NEW_PATH}" "${DYLIB}"
}

replace_rpaths () {
	local DYLIB="$1"
	local NEW_PATH="${2}"

	if [ "x${DYLIB}" = "x" ]; then
		return 1
	fi
	if [ "x${NEW_PATH}" = "x" ]; then
		return 1
	fi

	local FOUND_ENTRIES=$(otool -L "${DYLIB}" | grep "@rpath")

	if [ "x${FOUND_ENTRIES}" = "x" ]; then
		echo "File '${DYLIB}' does not contain any '@rpath' entries."
		return 0
	fi

	cp "${DYLIB}" "${DYLIB}.bak"
	echo "Trying to replace '@rpath' entries in '${DYLIB}'."

	local FOUND_PATHS=$(otool -L "${DYLIB}" | grep "@rpath" | sed -e 's/^[^@]*//g' -e 's/^\(.*\.dylib\).*$/\1/g')

	for FOUND_PATH in ${FOUND_PATHS}; do
		local LIB_FILE=$(echo "${FOUND_PATH}" | sed -e 's/@rpath\///g')
		local DYLIB_FILE=$(echo "${DYLIB}" | sed -e 's/^.*\///g')

		if [ ! -f "${LIB_FILE}" ]; then
			echo "Cannot find file '${LIB_FILE}'." >&2
			return 1
		fi

		local OLD_PATH="${FOUND_PATH}"
		local NEW_PATH="${DIR}/${LIB_FILE}"

		if [ "${LIB_FILE}" != "${DYLIB_FILE}" ]; then
			replace_rpath "${OLD_PATH}" "${NEW_PATH}" "${DYLIB}" || return 0
		else
			replace_id "${NEW_PATH}" "${DYLIB}" || return 0
		fi
	done

	return 0
}

for D in ./*dylib; do
	if [ -L "${D}" ]; then
		# File is a symbolic link.
		continue
	fi
	replace_rpaths "${D}" "${DIR}"
done

otool -L *.dylib | less
