dontcopy = /System/Library/% /usr/lib/% /usr/X11/lib/% /usr/X11R6/lib/% @executable_path/%
getdylibs = $(filter-out $(dontcopy),$(shell $(OTOOL) -L $(1) | tail -n +2 | awk '{print $$1}'))
dest = $(macos_bundle_path)/MacOS/$(notdir $(1))

# Let's create a list of all libraries used at runtime, starting with the
# application.

FILES :=
NEWFILES := $(USDX_BIN)

define processload
D := $(1)
ifeq ($$(patsubst @rpath%,,$$(D)),)
D := $$(firstword $$(foreach rpath,$$(RUNPATH),$$(wildcard $$(patsubst @rpath%,$$(rpath)%,$$(D))) ))
ifeq ($$(D),)
$$(error dylib $(1) not found in rpath $$(RUNPATH))
endif
else
ifeq ($$(patsubst @loader_path/%,,$$(D)),)
D := $$(patsubst @loader_path/%,$(2)%,$$(D))
endif
endif
$$(eval RUNPATH_$$(D) := $$$$(RUNPATH))
NEXTNEWFILES := $(NEXTNEWFILES) $$(filter-out $(FILES) $(NEXTNEWFILES),$$(D))
endef

define runpathlist
RUNPATH := $$(RUNPATH_$(1)) $$(patsubst @loader_path/%,$$(dir $(1))%,$$(filter-out $$(RUNPATH_$(1)),$$(shell $$(OTOOL) -l $(1) | grep -A 2 '\<cmd LC_RPATH\>' | sed -n 's/.* path \(.*\) .offset .*/\1/p')))
$$(foreach dylib,$$(call getdylibs,$(1)),$$(eval $$(call processload,$$(dylib),$$(dir $(1)))))
endef

define recurse
FILES := $$(FILES) $$(NEWFILES)
NEXTNEWFILES :=
$$(foreach dylib,$$(NEWFILES),$$(eval $$(call runpathlist,$$(dylib))))
NEWFILES := $$(strip $$(NEXTNEWFILES))
ifneq ($$(NEWFILES),)
$$(eval $$(recurse))
endif
endef

$(eval $(recurse))

# Libavutil is referenced as /usr/local/opt/ffmpeg@2.8/lib/libavutil.54.dylib by
# ultrastardx and as /usr/local/Cellar/ffmpeg@2.8/2.8.11/lib/libavutil.54.dylib
# by libavcodec. We don't want make to call the installdylib rule for both in
# parallel. Handle this by creating a variable libavutil.54.dylib that is
# assigned the full path. The last one wins.

define removedupes
FILE_$(1) := $(2)
endef

$(foreach dylib,$(FILES),$(eval $(call removedupes,$(notdir $(dylib)),$(dylib))))
FILES := $(sort $(foreach dylib,$(FILES),$(FILE_$(notdir $(dylib)))))

# The first rule in this file and thus the default target:
all: $(foreach dylib,$(FILES),$(call dest,$(dylib)))

define changeimport
	@echo change the install name for $(2)
	@$(INSTALL_NAME_TOOL) -change $(2) @executable_path/$(notdir $(2)) $(1)

endef

define installdylib
$(call dest,$(1)): $(1)
	@echo work on $(1)
	@$(INSTALL) -m 755  $(1) $(call dest,$(1))
ifneq ($(1),$(USDX_BIN))
	@$(INSTALL_NAME_TOOL) -id @executable_path/$(notdir $(1)) $(call dest,$(1))
endif
	$$(foreach dylib,$$(call getdylibs,$(1)),$$(call changeimport,$(call dest,$(1)),$$(dylib)))
endef

$(foreach dylib,$(FILES),$(eval $(call installdylib,$(dylib))))
