From 4fea1157a6ca8ae2ba6a5d68a95b9667f8a4dd18 Mon Sep 17 00:00:00 2001
From: Guillaume Pasero <guillaume.pasero@c-s.fr>
Date: Thu, 2 Mar 2017 16:09:23 +0100
Subject: [PATCH] BUG: Mantis-1364: remove old rpaths before adding a new one

---
 SuperBuild/Packaging/Files/macx_pkgsetup.in | 17 ++++++++++-------
 SuperBuild/Packaging/PackageHelper.cmake    |  6 +++++-
 2 files changed, 15 insertions(+), 8 deletions(-)

diff --git a/SuperBuild/Packaging/Files/macx_pkgsetup.in b/SuperBuild/Packaging/Files/macx_pkgsetup.in
index c196337ae9..c8dd077a83 100755
--- a/SuperBuild/Packaging/Files/macx_pkgsetup.in
+++ b/SuperBuild/Packaging/Files/macx_pkgsetup.in
@@ -28,9 +28,12 @@ EXE_FILES=$(find "$OUT_DIR/bin"  -type f -exec file {} \; | grep -i "Mach-O*.*ex
 for lib_file in $LIBRARY_FILES $EXE_FILES; do
     #echo "adding rpath to $OUT_DIR/$lib_file"
     if [ -f "$lib_file" ]; then
-	#echo "$INSTALL_NAME_TOOL -add_rpath $OUT_DIR/lib $lib_file"
-	$INSTALL_NAME_TOOL "-add_rpath" "$OUT_DIR/lib" "$lib_file"
-   fi
+      lib_file_original_rpaths=$(otool -l "$lib_file" | grep -A 3 "LC_RPATH" | grep -oE 'path .* \(offset' | cut -d ' ' -f 2)
+      for original_rpath in $lib_file_original_rpaths; do
+        $INSTALL_NAME_TOOL "-delete_rpath" "$original_rpath" "$lib_file"
+      done
+      $INSTALL_NAME_TOOL "-add_rpath" "$OUT_DIR/lib" "$lib_file"
+    fi
 done
 
 
@@ -50,10 +53,10 @@ if [ "$I_AM_XDK" = false ] ; then
     OTB_APP_FILES=$(find "$OUT_DIR/lib/otb/applications" -maxdepth 1 -type f)
     # run install_name_tool
     for app_file in $OTB_APP_FILES; do
-	#echo "adding rpath to $app_file"
-	if [ -f "$app_file" ]; then
-	    $INSTALL_NAME_TOOL "-add_rpath" "$OUT_DIR/lib" "$app_file"
-	fi
+      #echo "adding rpath to $app_file"
+      if [ -f "$app_file" ]; then
+        $INSTALL_NAME_TOOL "-rpath" "@ORIGINAL_RPATH_TO_REPLACE@" "$OUT_DIR/lib" "$app_file"
+      fi
     done
     
     rm -fr "Mapla.app"
diff --git a/SuperBuild/Packaging/PackageHelper.cmake b/SuperBuild/Packaging/PackageHelper.cmake
index dd42ddf4b4..9ef66b1a70 100644
--- a/SuperBuild/Packaging/PackageHelper.cmake
+++ b/SuperBuild/Packaging/PackageHelper.cmake
@@ -184,7 +184,11 @@ macro(macro_super_package)
       file(APPEND ${CMAKE_BINARY_DIR}/make_symlinks
         "${make_symlink_cmd}\n")
     endforeach()
-    
+
+    if(APPLE)
+      set(ORIGINAL_RPATH_TO_REPLACE ${DEPENDENCIES_INSTALL_DIR}/lib)
+    endif()
+
     configure_file(${PACKAGE_SUPPORT_FILES_DIR}/${PKGSETUP_IN_FILENAME}
       ${CMAKE_BINARY_DIR}/pkgsetup @ONLY)
     
-- 
GitLab