#!/bin/bash

APP="${1?}"
PLUGINS="${APP}/Contents/Plugins"
OP_PLUGINS="${APP}/Contents/Plugins/OpenPilot"
QT_LIBS="QtCore QtGui QtMultimedia QtMultimediaWidgets QtNetwork QtOpenGL QtPrintSupport QtQml QtQuick QtScript QtSerialPort QtSql QtSvg QtWidgets QtV8 QtXml"
QT_DIR=$(otool -L "${APP}/Contents/MacOS/OpenPilot GCS" | sed -n -e 's/\/QtCore\.framework.*//p' | sed -n -E 's:^.::p')
QT_EXTRA="accessible/libqtaccessiblewidgets.dylib bearer/libqgenericbearer.dylib imageformats/libqgif.dylib imageformats/libqico.dylib imageformats/libqjpeg.dylib imageformats/libqmng.dylib imageformats/libqtiff.dylib imageformats/libqsvg.dylib qmltooling/libqmldbg_tcp.dylib sqldrivers/libqsqlodbc.dylib sqldrivers/libqsqlpsql.dylib sqldrivers/libqsqlite.dylib imageformats/libqtga.dylib iconengines/libqsvgicon.dylib"

OSG_EXTRA="libosgViewer.90.dylib"

if [ -z "${QT_DIR}" ]
then
    # QT_DIR is empty, then we have (presumably):
    QT_FRAMEWORKS="/Library/Frameworks"
    QT_PLUGINS="/Developer/Applications/Qt/plugins"
else
    # Typical Nokia SDK paths
    QT_FRAMEWORKS="${QT_DIR}"
    QT_PLUGINS="${QT_DIR}/../plugins"
    QT_DIR="${QT_DIR}/"
fi

echo "Qt library directory is \"${QT_DIR}\""

echo "Running macdeployqt from ${QT_DIR}../bin/macdeployqt"

"${QT_DIR}../bin/macdeployqt" "${APP}" -no-strip -verbose=2

#Append Qml2Imports config to qt.conf
echo "Qml2Imports = Imports" >> "${APP}/"Contents/Resources/qt.conf

echo "Processing Qt libraries paths in ${APP}"
for f in "${PLUGINS}/"*.dylib "${OP_PLUGINS}/"*.dylib "${APP}/"Contents/Imports/QtQuick.2/*.dylib "${APP}/"Contents/Imports/QtQuick/*/*.dylib
do
    if [ -f "${f}" ] && [ ! -L "${f}" ]
    then
        # Only process plain files
        chmod +w "${f}"
        echo "* ${f}"
        for g in $QT_LIBS
        do
            install_name_tool -change \
                "${QT_DIR}${g}.framework/Versions/5/${g}" \
                @executable_path/../Frameworks/${g}.framework/Versions/5/${g} \
                "${f}"
        done
        chmod -w "${f}"
    fi
done

echo "Copying SDL"
cp -a "/Library/Frameworks/SDL.framework" "${APP}/Contents/Frameworks/"
chmod +w "${APP}/Contents/Plugins/libsdlgamepad.1.dylib"
chmod +w "${APP}/Contents/Frameworks/SDL.framework/SDL"
echo "Changing package identification of SDL"
install_name_tool -id \
    @executable_path/../Frameworks/SDL.framework/SDL \
    "${APP}/Contents/Frameworks/SDL.framework/SDL"
install_name_tool -change \
    @rpath/SDL.framework/Versions/A/SDL \
    "@executable_path/../Frameworks/SDL.framework/SDL" \
    "${APP}/Contents/Plugins/libsdlgamepad.1.dylib"
chmod -w "${APP}/Contents/Plugins/libsdlgamepad.1.dylib"
chmod -w "${APP}/Contents/Frameworks/SDL.framework/SDL"

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