#!/bin/bash

APP="${1?}"
PLUGINS="${APP}/Contents/Plugins"
OP_PLUGINS="${APP}/Contents/Plugins/OpenPilot"
QT_LIBS="QtGui QtCore QtSvg QtSql QtOpenGL QtNetwork QtXml QtDBus QtScript phonon"

echo "Processing Qt libraries in $1"
macdeployqt "${APP}"

for f in "${PLUGINS}/"*.dylib "${OP_PLUGINS}/"*.dylib
do
    for g in $QT_LIBS
    do
	install_name_tool -change \
	    ${g}.framework/Versions/4/${g} \
	    @executable_path/../Frameworks/${g}.framework/Versions/4/${g} \
	    "${f}"
    done
done

# should be redundant but some libs missed by main app and macdeployqt
for f in ${QT_LIBS}
do
    echo "Copying ${f}"
    cp -r /Library/Frameworks/${f}.framework "${APP}/Contents/Frameworks/"

    echo "Changing package identification of ${f}"
    install_name_tool -id \
	@executable_path/../Frameworks/${f}.framework/Versions/4/QtCore \
	"${APP}/Contents/Frameworks/${f}.framework/Versions/4/${f}"

    echo "Changing package linkages"
    for g in $QT_LIBS
    do
	install_name_tool -change \
	    ${g}.framework/Versions/4/${g} \
	    @executable_path/../Frameworks/${g}.framework/Versions/4/${g} \
	    "${APP}/Contents/Frameworks/${f}.framework/Versions/4/${f}"
    done
done

# deleting unnecessary files
echo "Deleting unnecessary files"
find "${APP}/Contents/Frameworks" -iname "current" -exec rm -rf \{\} \;
find "${APP}/Contents/Frameworks" -iname "4.0" -exec rm -rf \{\} \;
find "${APP}/Contents/Frameworks" -iname "*_debug" -exec rm -rf \{\} \;