#!/bin/bash
#
# Fixes Regina's MacOS app bundle to use @loader_path instead of
# @executable_path when linking against other shared libraries inside
# the app bundle.
#
# This is important if, for instance, we wish to be able to load Regina's
# python module from a different python session (e.g., SnapPy).
#
#
# Usage: fix-bundle-paths <bundle_dir>
#
#
# Copyright (c) 2013-2016, Ben Burton
# For further details contact Ben Burton (bab@debian.org).
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# As an exception, when this program is distributed through (i) the
# App Store by Apple Inc.; (ii) the Mac App Store by Apple Inc.; or
# (iii) Google Play by Google Inc., then that store may impose any
# digital rights management, device limits and/or redistribution
# restrictions that are required by its terms of service.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
set -e

if [ ! -d "$1" ]; then
    echo "Usage: fix-bundle-paths <bundle_dir>"
    exit 1
fi

maindir="$1/Contents/MacOS"
pydir="$maindir/python"

cd "$maindir"
for file in *.dylib; do
    if [ -f "$file" -a ! -h "$file" ]; then
        libs=`otool -L "$file" | grep '@executable_path' | \
            grep -v "/$file " | cut -d' ' -f1`
        echo "Processing: $file"
        for old in $libs; do
            echo "Fixing: $old"
            new=`echo "$old" | sed -e 's#@executable_path/../MacOS#@loader_path#'`
            install_name_tool -change "$old" "$new" "$file"
        done
    fi
done

cd python/regina
file=engine.so
libs=`otool -L "$file" | grep '@executable_path' | cut -d' ' -f1`
echo "Processing: $file"
for old in $libs; do
    echo "Fixing: $old"
    new=`echo "$old" | sed -e 's#@executable_path/../MacOS#@loader_path/../..#'`
    install_name_tool -change "$old" "$new" "$file"
done

