#!/bin/bash
# Copyright Matt Broadstone

APPDIR=.
APPNAME=flo
APPNAME2=flo.app
APP=$APPDIR/bin/$APPNAME.app

QTLIB=/Library/Frameworks
QTPLUGIN=/Developer/Applications/Qt/plugins/

MODULES="Core Gui Network Sql Svg Xml" 
PLUGINS="imageformats sqldrivers"

echo "Copying and linking modules:"
mkdir $APP/Contents/Frameworks
for module in $MODULES
do
    echo "    > $module" 
    mkdir -p $APP/Contents/Frameworks/Qt$module.framework/Versions/4/
    cp -Rv $QTLIB/Qt$module.framework/Versions/4/Qt$module $APP/Contents/Frameworks/Qt$module.framework/Versions/4/Qt$module
    install_name_tool -id @executable_path/../Frameworks/Qt$module.framework/Versions/4/Qt$module \
                          $APP/Contents/Frameworks/Qt$module.framework/Versions/4/Qt$module
    install_name_tool -change $QTLIB/Qt$module.framework/Versions/4/Qt$module \
                              @executable_path/../Frameworks/Qt$module.framework/Versions/4/Qt$module \
                              $APP/Contents/MacOS/$APPNAME

    if [[ "$module" != "Core" ]]; then
        install_name_tool -change $QTLIB/QtCore.framework/Versions/4/QtCore \
                                  @executable_path/../Frameworks/QtCore.framework/Versions/4/QtCore \
                                  $APP/Contents/Frameworks/Qt$module.framework/Versions/4/Qt$module 
    fi
    if [[ "$module" == "Svg" ]]; then
        install_name_tool -change $QTLIB/QtXml.framework/Versions/4/QtXml \
                                  @executable_path/../Frameworks/QtXml.framework/Versions/4/QtXml \
                                  $APP/Contents/Frameworks/Qt$module.framework/Versions/4/Qt$module
        install_name_tool -change $QTLIB/QtGui.framework/Versions/4/QtGui \
                                  @executable_path/../Frameworks/QtGui.framework/Versions/4/QtGui \
                                  $APP/Contents/Frameworks/Qt$module.framework/Versions/4/Qt$module
    fi
done

echo "Copying and linking plugins:"
mkdir $APP/Contents/Plugins
for plugindir in $PLUGINS
do
    mkdir $APP/Contents/Plugins/$plugindir
    cp -R $QTPLUGIN/$plugindir/* $APP/Contents/Plugins/$plugindir
    for plugin in `ls $APP/Contents/Plugins/$plugindir`
    do
        echo "    > $plugindir/$plugin"
        install_name_tool -change $QTLIB/QtGui.framework/Versions/4/QtGui \
                                  @executable_path/../Frameworks/QtGui.framework/Versions/4/QtGui \
                                  $APP/Contents/Plugins/$plugindir/$plugin
        install_name_tool -change $QTLIB/QtCore.framework/Versions/4/QtCore \
                                  @executable_path/../Frameworks/QtCore.framework/Versions/4/QtCore \
                                  $APP/Contents/Plugins/$plugindir/$plugin
    done 
done

cd $APPDIR/bin
mkdir $APPNAME
cp -r $APPNAME2 $APPNAME

hdiutil create -volname "$APPNAME" -srcfolder $APPNAME -ov $APPNAME.dmg
rm -rf $APPNAME


