#!/bin/bash

set -e

HERE="$(cd "$(dirname "$0")"; pwd)"
FRAMEWORK="$(cd "$1"; pwd)"
PYTHON_VERSION_MAJOR=$(readlink "$FRAMEWORK/Versions/Current")

# When rewriting the paths we need to reference the original framework
# location as it was used for building.
ORIGINAL_FRAMEWORK_PATH="$(cd "$HERE/../build"; pwd)/tmp/out/Python.framework"

install_name_tool \
  -change "$ORIGINAL_FRAMEWORK_PATH/Versions/$PYTHON_VERSION_MAJOR/Python" \
  @rpath/Python \
  "$FRAMEWORK/Versions/$PYTHON_VERSION_MAJOR/bin/python"
install_name_tool \
  -add_rpath @executable_path/../ \
  "$FRAMEWORK/Versions/$PYTHON_VERSION_MAJOR/bin/python"
install_name_tool \
  -change "$ORIGINAL_FRAMEWORK_PATH/Versions/$PYTHON_VERSION_MAJOR/Python" \
  @rpath/Python \
  "$FRAMEWORK/Versions/$PYTHON_VERSION_MAJOR/Resources/Python.app/Contents/MacOS/Python"
install_name_tool \
  -add_rpath @executable_path/../../../../ \
  "$FRAMEWORK/Versions/$PYTHON_VERSION_MAJOR/Resources/Python.app/Contents/MacOS/Python"
chmod u+w "$FRAMEWORK/Python"
otool -D "$FRAMEWORK/Python"
install_name_tool -id @rpath/Python "$FRAMEWORK/Python"

SITE="$FRAMEWORK/Versions/$PYTHON_VERSION_MAJOR/lib/python$PYTHON_VERSION_MAJOR"
DYLD_SITE="$SITE/lib-dynload"

# At this point we need to rewrite SSL to work the way we want.
cp /usr/local/opt/openssl/lib/*.dylib $DYLD_SITE
"$HERE/make-openssl-relocatable" "$DYLD_SITE"

# Trash unwanted things.  This should be more specific but honestly, this is just
# for saving space so every little bit helps.
rm -rf "$SITE/plat-mac"
rm -rf "$SITE/lib2to3"
rm -rf "$SITE/lib-tk"
rm -rf "$SITE/idlelib"
rm -rf "$SITE/ensurepip"
rm -rf "$SITE/bsddb"
rm -rf "$SITE/lib-dynload/_Qt.so"
rm -rf "$SITE/lib-dynload/_CF.so"
rm -rf "$SITE/lib-dynload/_File.so"
for testdir in $(find "$SITE" -type d -name 'test'); do
  rm -rf "$testdir"
done
