#!/bin/bash
~/.local/bin/gtk-mac-bundler darktable.bundle
sed -i '' 's|/opt/local/share/locale||' package/darktable.app/Contents/Resources/etc/gtk-2.0/gtk.immodules
if pkg-config --atleast-version=1.32.5 pango
then
	sed -i '' 's|@executable_path/.*/||' package/darktable.app/Contents/Resources/etc/pango/pango.modules
else
	sed -i '' 's|@executable_path|../..|' package/darktable.app/Contents/Resources/etc/pango/pango.modules
fi
sed -i '' 's|{VERSION}|'$(git describe --tags --long --match '*[0-9.][0-9.][0-9]'|cut -d- -f2|sed 's/^\([0-9]*\.[0-9]*\)$/\1.0/')'|' package/darktable.app/Contents/Info.plist
sed -i '' 's|{COMMITS}|'$(git describe --tags --long --match '*[0-9.][0-9.][0-9]'|cut -d- -f3)'|' package/darktable.app/Contents/Info.plist
rm package/darktable.app/Contents/Resources/etc/pango/pangorc
touch package/darktable.app/Contents/Resources/etc/pango/pangorc
find package/darktable.app/Contents/MacOS/darktable-bin package/darktable.app/Contents/MacOS/darktable-cli-bin package/darktable.app/Contents/Resources/lib/darktable -type f -exec \
  install_name_tool -change @executable_path/../lib/darktable/libdarktable.dylib @executable_path/../Resources/lib/darktable/libdarktable.dylib \{} \;
ln -s /Applications package/

if [ -z "$STRIPDEBUGINFO" ]
then
	find package/darktable.app/Contents/Resources/lib/darktable \( -name \*.dylib -or -name \*.so \) -exec dsymutil \{} \;
	dsymutil package/darktable.app/Contents/MacOS/darktable-bin
	dsymutil package/darktable.app/Contents/MacOS/darktable-cli-bin
fi

PROGN=darktable

# Creating temporary rw image
hdiutil create -srcfolder package -volname "${PROGN}" -fs HFS+ \
      -fsargs "-c c=64,a=16,e=16" -format UDRW pack.temp.dmg

# mounting image without autoopen to create window style params
device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \
         egrep '^/dev/' | sed 1q | awk '{print $1}')
echo '
 tell application "Finder"
	tell disk "'${PROGN}'"
		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, 100, 885, 330}
		set theViewOptions to the icon view options of container window
		set arrangement of theViewOptions to not arranged
		set icon size of theViewOptions to 72
		set position of item "'${PROGN}'" of container window to {100, 100}
		set position of item "Applications" of container window to {375, 100}
		update without registering applications
		close
		open
		delay 5
	end tell
 end tell
' | osascript

# Finalizing creation 
chmod -Rf go-w /Volumes/"${PROGN}"
sync
hdiutil detach ${device}
hdiutil convert "pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${PROGN}"-$(git describe --tags|sed 's/^release-//;s/-/+/;s/-/~/;s/rc/~rc/')
rm -f pack.temp.dmg 
rm -Rf package
