#!/bin/sh
VERSION=0.2.0
eval `grep VERSION qiph.pro | awk '{print $3}'`
echo $VERSION

rm -rf build
qmake
xcodebuild clean
xcodebuild || exit
mkdir build/Default/qiph.app/Contents/Resources
cp -a osx/* build/Default/qiph.app/Contents/Resources/
cp misc/fftheofwd.sh build/Default/qiph.app/Contents/Resources/


##############################################################################
follow_dependencies () {
    libname=$1
    cd "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks"
    dependencies=`otool -arch all -L "$libname"  | egrep '\/(opt|usr)\/local\/lib' | awk '{print $1}'`
    for l in $dependencies; do
        depname=`basename $l`
        deppath=`dirname $l`
        if [ ! -f "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks/$depname" ]; then
            deploy_lib $depname "$deppath"
        fi
    done

    FW=/Library/Frameworks/
    QTLIBS=`otool -arch all -L "$libname" | egrep 'Qt.*framework' | awk '{print $1}'`
    for l in $QTLIBS; do
        depname=`basename $l`
        deppath=`dirname ${FW}$l`
        if [ ! -f "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks/$depname" ]; then
            deploy_lib $depname "$deppath"
            update_links $libname `dirname $l`
        fi
    done
}

update_links () {
    libname=$1
    libpath=$2
    echo "@@@ update $libpath / $libname"
    for n in `ls $LIBS_PATH/*`; do
        install_name_tool \
            -change "$libpath/$libname" \
            @executable_path/../Frameworks/$libname \
            "$n"
    done
}

deploy_lib () {
    libname=$1
    libpath=$2
    check=`echo $INSTALLED | grep $libname`
    if [ "X$check" = "X" ]; then
        if [ ! -f "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks/$libname" ]; then
            cp -f "$libpath/$libname" "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks/$libname"
            install_name_tool \
                -id @executable_path/../Frameworks/$libname \
                "$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks/$libname"
            follow_dependencies $libname
        fi
        export INSTALLED="$INSTALLED $libname"
    fi
    update_links $libname $libpath
}

update_executable() {
    echo "updating executable ${TARGET}"
    LIBS=`otool -arch all -L "$TARGET" | egrep '\/(opt|usr)\/local\/lib' | awk '{print $1}'`
    for l in $LIBS; do
        libname=`basename $l`
        libpath=`dirname $l`
        deploy_lib $libname $libpath
        install_name_tool \
            -change $libpath/$libname \
            @executable_path/../Frameworks/$libname \
            "$TARGET"
    done

    FW=/Library/Frameworks/
    QTLIBS=`otool -arch all -L "$TARGET" | egrep 'Qt.*framework' | awk '{print $1}'`
    for l in $QTLIBS; do
        libname=`basename $l`
        libpath=`dirname ${FW}$l`
        deploy_lib $libname $libpath
        install_name_tool \
            -change ${l} \
            @executable_path/../Frameworks/$libname \
            "$TARGET"
        update_links $libname `dirname $l`
    done
}
##############################################################################

echo "------------------------------------"

##############################################################################
# add dependancies..
export TARGET_BUILD_DIR="$(pwd)/build/Default/"
export PRODUCT_NAME="qiph"
export INSTALLED=""
export LIBS_PATH="$TARGET_BUILD_DIR/${PRODUCT_NAME}.app/Contents/Frameworks"
export TARGET="$TARGET_BUILD_DIR/${PRODUCT_NAME}.app/Contents/MacOS/${PRODUCT_NAME}"
BGPIC=$(pwd)/misc/dmgbg.png

echo "BASEDIR: ${TARGET_BUILD_DIR}"
echo "TARGET : ${TARGET}"
echo "LIBDIR : ${LIBS_PATH}"

echo "------------------------------------"

mkdir -p $LIBS_PATH
rm -f $LIBS_PATH/*.dylib

update_executable

echo "getting dependent libs.."

cd $LIBS_PATH && MORELIBS=`otool -arch all -L * | egrep '\/(opt|usr)\/local\/lib' | awk '{print $1}'` && cd -
while [ "X$MORELIBS" != "X" ]; do
    for l in $MORELIBS; do
        libname=`basename $l`
        libpath=`dirname $l`
        deploy_lib "$libname" "$libpath"
    done
    cd $LIBS_PATH && MORELIBS=`otool -arch all -L * | egrep '\/(opt|usr)\/local\/lib' | awk '{print $1}'` && cd -
done
update_executable

##############################################################################
# stript 64bit versions from frameworks. 
echo "STRIP 64bit dylibs"
cd $LIBS_PATH || exit 1
cd ..
mv Frameworks fwold
mkdir Frameworks
for file in $(ls fwold); do
  lipo fwold/$file -remove x86_64 -output Frameworks/$file || \
  cp fwold/$file Frameworks/$file
done
rm -rf fwold

##############################################################################
#deploy .nib

mkdir -p "$TARGET_BUILD_DIR/${PRODUCT_NAME}.app/Contents/Resources/"
cp -a /Library/Frameworks/QtGui.framework/Versions/4/Resources/qt_menu.nib \
  "$TARGET_BUILD_DIR/${PRODUCT_NAME}.app/Contents/Resources/"



##############################################################################
###roll a DMG

VOLNAME=qiph       # name of the DMG Installer Volume
DMGFILE=/tmp/qiph-$VERSION-osx_intel.dmg

##############################################################################
###roll a DMG
echo "generating DMG.."

export PRODUCT_NAME
TMPFILE=/tmp/qiphtmp.dmg
MNTPATH=/tmp/qiphmnt/
APPNAME="${PRODUCT_NAME}.app"

mkdir -p $MNTPATH
if [ -e $TMPFILE -o -e $DMGFILE -o ! -d $MNTPATH ]; then
  echo
  echo "can not create DMG. tmp-file or destination file exists."
  echo "please clean up previous builds."
  exit;
fi

hdiutil create -megabytes 200 $TMPFILE
DiskDevice=$(hdid -nomount "${TMPFILE}" | grep Apple_HFS | cut -f 1 -d ' ')
newfs_hfs -v "${VOLNAME}" "${DiskDevice}"
mount -t hfs "${DiskDevice}" "${MNTPATH}"

cp -r ${TARGET_BUILD_DIR}/${PRODUCT_NAME}.app ${MNTPATH}/
mkdir ${MNTPATH}/.background
BGFILE=$(basename $BGPIC)
cp -vi ${BGPIC} ${MNTPATH}/.background/${BGFILE}

echo '
   tell application "Finder"
     tell disk "'${VOLNAME}'"
       open
       set current view of container window to icon view
       set toolbar visible of container window to false
       set statusbar visible of container window to false
       set the bounds of container window to {400, 200, 800, 440}
       set theViewOptions to the icon view options of container window
       set arrangement of theViewOptions to not arranged
       set icon size of theViewOptions to 64
       set background picture of theViewOptions to file ".background:'${BGFILE}'"
       make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
       set position of item "'${APPNAME}'" of container window to {100, 100}
       set position of item "Applications" of container window to {310, 100}
       close
       open
       update without registering applications
       delay 5
       eject
     end tell
   end tell
' | osascript

sync

# Umount the image
umount "${DiskDevice}"
hdiutil eject "${DiskDevice}"

# Create a read-only version, use zlib compression
hdiutil convert -format UDZO "${TMPFILE}" -imagekey zlib-level=9 -o "${DMGFILE}"

# Delete the temporary files
if [ -z "$KEEPTMP" ]; then
  rm $TMPFILE
fi
rmdir $MNTPATH

echo
echo "packaging suceeded."
if [ -n "$KEEPTMP" ]; then
 ls -l $TMPFILE
fi
ls -l $DMGFILE || exit

echo -n "UPLOAD? [enter|CTRL-C]" ; read
rsync -P $DMGFILE rg42.org:/var/sites/inout/docroot/software/
