#!/bin/sh
APPNAME="QCTools"
SIGNATURE="MediaArea.net"
BUNDLEID="net.mediaarea.qctools.mac"

DMG="tmp-${APPNAME}.dmg"
FILES="tmp-${APPNAME}"

# Create the package
rm -rf "${FILES}"
rm -f "${DMG}"
rm -f "${APPNAME}.dmg"

mkdir "${FILES}"
mkdir "${FILES}/.background"
cp -R "../QtCreator/build/qctools-gui/${APPNAME}.app" "${FILES}/"
rm -fr "${FILES}/${APPNAME}.app/Contents/Frameworks"
rm -fr "${FILES}/${APPNAME}.app/Contents/Library"

codesign -f --deep --options=runtime -s "Developer ID Application: ${SIGNATURE}" -i "${BUNDLEID}" --verbose "${FILES}/${APPNAME}.app/Contents/MacOS/${APPNAME}"
codesign -f --deep --options=runtime -s "Developer ID Application: ${SIGNATURE}" --verbose "${FILES}/${APPNAME}.app"

cp ../../License.html "${FILES}/License.html"
cp ../../History.txt "${FILES}/History.txt"
cp Logo_White.icns "${FILES}/.background/Logo_White.icns"

# Create the disk image
hdiutil create "$DMG" -ov -fs HFS+ -format UDRW -volname "${APPNAME}" -srcfolder "${FILES}"

DEVICE=$(hdiutil attach -readwrite -noverify "${DMG}" | egrep '^/dev/' | sed 1q | awk '{print $1}')
sleep 2

pushd /Volumes/"${APPNAME}"
ln -s /Applications
rm -f .DS_Store
popd

echo '
   tell application "Finder"
     tell disk "'${APPNAME}'"
           open
           set current view of container window to icon view
           set toolbar visible of container window to false
           set the bounds of container window to {400, 100, 962, 600}
           set viewOptions to the icon view options of container window
           set arrangement of viewOptions to not arranged
           set icon size of viewOptions to 72
           set background picture of viewOptions to file ".background:Logo_White.icns"
           set position of item "'${APPNAME}'.app" of container window to {125, 175}
           set position of item "Applications" of container window to {275, 200}
           set position of item "License.html" of container window to {450, 175}
           set position of item "History.txt" of container window to {450, 275}
           close
     end tell
   end tell
' | osascript

hdiutil detach "${DEVICE}"
sleep 2

# convert to compressed image, delete temp image
hdiutil convert "$DMG" -format UDBZ -o "${APPNAME}.dmg"
codesign -f --deep --options=runtime -s "Developer ID Application: ${SIGNATURE}" -i "${BUNDLEID}" --verbose "${APPNAME}.dmg"

rm -rf "${FILES}"
rm -f "$DMG"
