#!/bin/sh

if [ $# -ne 2 ]; then
  echo "usage: $0 appbundle.app binary"
  exit 1
fi

BUNDLE=$1
BINARY_NAME=$2
BINARY=${BUNDLE}/Contents/MacOS/${BINARY_NAME}

FRAMEWORKS_DIR=${BUNDLE}/Contents/Frameworks
mkdir -p ${FRAMEWORKS_DIR} 

name_in_bundle() {
  ORIG=${1}
  ORIG_BASENAME=`basename ${ORIG}`
  echo "@executable_path/../Frameworks/${ORIG_BASENAME}"
}

rename_the_sub_lib() {
  IN=$1
  OLD_PATH=$2
  NEW_PATH=`name_in_bundle ${OLD_PATH}`
  #echo "Renaming ${OLD_PATH} to ${NEW_PATH} in ${IN}"
  install_name_tool -change ${OLD_PATH} ${NEW_PATH} ${IN}
}

cp_the_lib () {
  LIB=$1
  LIB_NAME=`basename $1`
  NEW_PATH=`name_in_bundle $1`

  echo "Copying ${LIB_NAME} to private framework, was ${LIB}"
  cp ${LIB} ${FRAMEWORKS_DIR}
  chmod u+w ${FRAMEWORKS_DIR}/${LIB_NAME}
  install_name_tool -id ${NEW_PATH} ${FRAMEWORKS_DIR}/${LIB_NAME}
}

non_vanilla_libs_from () {
  FROM=$1
  PATTERN=$2
  otool -L ${FROM} | sed -e '1d' | cut -f 1 -d ' ' | grep ${PATTERN} | grep -v ${FROM}
}

non_vanilla_libs () {
  FROM=$1
  non_vanilla_libs_from ${FROM} /usr/local
  non_vanilla_libs_from ${FROM} /opt/local
  non_vanilla_libs_from ${FROM} ${HOME}
}


NEW_LIBS=`non_vanilla_libs ${BINARY}`
ALL_LIBS="${NEW_LIBS}"
while [ "${NEW_LIBS}" ]; do
  OLD_LIBS=${NEW_LIBS}
  NEW_LIBS=""
  for i in ${OLD_LIBS}; do
    NEW_LIBS="${NEW_LIBS} `non_vanilla_libs ${i}`"
    cp_the_lib ${i}
  done
  ALL_LIBS="${ALL_LIBS} ${NEW_LIBS}"
done

THE_FRAMEWORKS=`non_vanilla_libs_from ${BINARY} "\.framework"`
for i in ${THE_FRAMEWORKS}; do
  cp -r /Library/Frameworks/${i} ${FRAMEWORKS_DIR}
done

for i in ${BINARY} ${FRAMEWORKS_DIR}/*.dylib; do
  for a in ${ALL_LIBS}; do
    rename_the_sub_lib ${i} ${a}
  done
done
