#!/bin/bash

# script for pulling together a MacOSX app bundle.

GTKSTACK_ROOT=$HOME/gtk/inst
ARDOURSTACK_ROOT=$HOME/a3/inst
PGROOT=/Users/paul/gtk/inst
PAROOT=/Users/paul/a3/inst
BUILD_ROOT=../..

if pkg-config --modversion gtk+-2.0 | grep -s 2.22 ; then
    # older GTK
    GDKPIXBUF_LOADERS=$GTKSTACK_ROOT/lib/gtk-2.0/2.10.0/loaders
    echo 
    echo
    echo "*****************************************************"
    echo "You are building with the OLD GTK stack. I hope that is ok"
    echo "*****************************************************"
    echo
    echo
else
    # newer GTK
    GDKPIXBUF_LOADERS=$GTKSTACK_ROOT/lib/gdk-pixbuf-2.0/2.10.0/loaders
    echo 
    echo
    echo "*****************************************************"
    echo "You are building with the NEW GTK stack. I hope that is ok"
    echo "*****************************************************"
    echo
    echo
fi

SAE=
MIXBUS=
INTERNAL_JACK=1
WITH_LADSPA=1
STRIP=1
PRINT_SYSDEPS=
WITH_NLS=
EXTERNAL_JACK=
BINNAME=Ardour2
APPNAME=Ardour
BUILT_EXECUTABLE=ardour
GDK_LOADERS=gdk-pixbuf-2.0/2.10.0

while [ $# -gt 0 ] ; do
    echo "arg = $1"
    case $1 in

	#
	# top level build targets
	#

	--sae) WITH_NLS= ; 
               SAE=1 ; 
	       INTERNAL_JACK=1; 
	       WITH_LADSPA=1; 
               STRIP= ; 
	       PRODUCT_PKG_DIR=ArdourSAE ; 
	       shift ;;
	--mixbus) MIXBUS=1; 
	          WITH_NLS=1 ; 
                  SAE= ; 
                  INTERNAL_JACK=; 
                  WITH_LADSPA=; 
                  STRIP=1 ; 
		  PRODUCT_PKG_DIR=Mixbus2;
		  APPNAME=Mixbus2 ;
  	          BINNAME=Mixbus2 ;
		  BUILT_EXECUTABLE=mixbus ;
                  shift ;;
	--public) WITH_NLS=1 ; 
	          SAE= ; 
		  INTERNAL_JACK=; 
                  WITH_LADSPA=1; 
                  STRIP= ; 
		  PRODUCT_PKG_DIR=Ardour;
		  shift ;;
	--allinone) SAE= ; 
	            WITH_NLS= ; 
		    INTERNAL_JACK=1; 
		    WITH_LADSPA=1; 
		    STRIP= ; 
		    PRODUCT_PKG_DIR=Ardour ;
		    shift ;;
	--test) SAE= ; INTERNAL_JACK=; WITH_LADSPA=; STRIP= ; shift ;;
	
	--old-stack) GDK_LOADERS=gtk-2.0/2.10.0 ; shift ;;

	#
	# specific build flags
	#

	--nojack) INTERNAL_JACK= ; shift ;;
	--noladspa) WITH_LADSPA= ; shift ;;
	--nostrip) STRIP= ; shift ;;
	--sysdeps) PRINT_SYSDEPS=1; shift ;;
	--nls) WITH_NLS=1 ; shift ;;
	--external_jack) EXTERNAL_JACK=$2; shift ; shift ;;
    esac
done

if [ x$EXTERNAL_JACK != x -a x$INTERNAL_JACK != x ] ; then
    echo "It makes no sense to package JACK internally and externally. Please pick one."
fi

if [ x$MIXBUS != x ] ; then
    release_version=`grep -m 1 '^mixbus_version' ../../SConstruct | cut -d' ' -f 3 | sed "s/'//g"`
else
    release_version=`grep -m 1 '^ardour_version' ../../SConstruct | cut -d' ' -f 3 | sed "s/'//g"`
fi
svn_version=`grep -m 1 'svn_revision =' ../../libs/ardour/svn_revision.cc | cut -d' ' -f 6 | sed 's/[";]//g'`
echo "Version is $release_version / $svn_version"

info_string="$release_version/$svn_version built on `hostname` by `whoami` on `date`"
echo "Info string is $info_string"

# setup directory structure

APPDIR=${APPNAME}.app
APPROOT=$APPDIR/Contents
Frameworks=$APPROOT/lib
Resources=$APPROOT/Resources
Plugins=$APPROOT/Plugins
Surfaces=$APPROOT/Surfaces
Shared=$Resources/share
Etc=$Resources/etc
Locale=$Resources/locale

if [ x$PRINT_SYSDEPS != x ] ; then
#
# print system dependencies
#

    for file in $APPROOT/MacOS/* $Frameworks/* $Frameworks/modules/* $Plugins/*.so ; do 
	if ! file $file | grep -qs Mach-O ; then
	    continue
	fi
	otool -L $file | awk '{print $1}' | egrep -v "(^@executable_path|^Ardour[0-9][.0-9]*.app)" 
    done | sort | uniq
    exit 0
fi

echo "Removing old $APPDIR tree ..."

rm -rf $APPDIR

echo "Building new app directory structure ..."

# only bother to make the longest paths

mkdir -p $APPROOT/MacOS
mkdir -p $APPROOT/Resources
mkdir -p $APPROOT/Plugins
mkdir -p $APPROOT/Surfaces
mkdir -p $Frameworks/modules
mkdir -p $Shared/templates
mkdir -p $Etc

# maybe set variables
env=""
if test x$SAE != x ; then
    appname="Ardour2/SAE"
    env="$env<key>ARDOUR_SAE</key><string>true</string>"
    #
    # current default for SAE version is German keyboard layout without a keypad
    #
    env="$env<key>ARDOUR_KEYBOARD_LAYOUT</key><string>de-nokeypad</string>"
    env="$env<key>ARDOUR_UI_CONF</key><string>ardour2_ui_sae.conf</string>"
    env="$env<key>ARDOUR2_UI_RC</key><string>ardour2_ui_dark_sae.rc</string>"
elif test x$MIXBUS != x ; then
    appname="Mixbus2"
    env="$env<key>ARDOUR_MIXBUS</key><string>true</string>"
    #
    # current default for MIXBUS version is US keyboard layout without a keypad
    #
    env="$env<key>ARDOUR_KEYBOARD_LAYOUT</key><string>us-nokeypad</string>"
else
    appname="Ardour2"
fi

#
# if we're not going to bundle JACK, make sure we can find
# jack in the places where it might be
#

if test x$INTERNAL_JACK != x ; then
    env="$env<key>ARDOUR_INTERNAL_JACK</key><string>true</string>"
else
    env="$env<key>PATH</key><string>/usr/local/bin:/opt/bin</string>"
    env="$env<key>DYLIB_FALLBACK_LIBRARY_PATH</key><string>/usr/local/lib:/opt/lib</string>"
fi

env="<key>LSEnvironment</key><dict><key>ARDOUR_BUNDLED</key><string>true</string>$env</dict>"

# edit plist
sed -e "s?@ENV@?$env?g" \
    -e "s?@APPNAME@?$appname?g" \
    -e "s?@VERSION@?$release_version/$svn_version?g" \
    -e "s?@INFOSTRING@?$info_string?g" < Info.plist.in > Info.plist
# and plist strings
sed -e "s?@APPNAME@?$appname?" \
    -e "s?@ENV@?$env?g" \
    -e "s?@VERSION@?$release_version/$svn_version?g" \
    -e "s?@INFOSTRING@?$info_string?g" < InfoPlist.strings.in > Resources/InfoPlist.strings

# copy static files

cp Info.plist $APPROOT
cp -R Resources $APPROOT

#
# if we build a bundle without jack, then
# make the Ardour2 executable a helper
# script that checks to see if JACK is
# installed.
#

if test x$INTERNAL_JACK != x ; then
    MAIN_EXECUTABLE=$BINNAME
else
    cp startup_script $APPROOT/MacOS/Ardour2
    chmod 775 $APPROOT/MacOS/$BINNAME
    MAIN_EXECUTABLE=$BINNAME.bin
fi

echo "Copying main executable ...."
cp ../../gtk2_ardour/$BUILT_EXECUTABLE-$release_version $APPROOT/MacOS/$MAIN_EXECUTABLE
if test x$SAE != x ; then
    # cp ../../gtk2_ardour/evtest $APPROOT/MacOS/gtkevents
    cp  Ardour2-SAE.icns $Resources/appIcon.icns
elif test x$MIXBUS != x ; then
    cp  Mixbus.icns $Resources/appIcon.icns
else
    cp  Ardour2.icns $Resources/appIcon.icns
fi
if test x$STRIP != x ; then
    strip $APPROOT/MacOS/$MAIN_EXECUTABLE
fi
if test x$INTERNAL_JACK != x ; then
    if [ -f /usr/local/lib/jack/jack_coreaudio.so ] ; then 
	cp /usr/local/lib/jack/jack_coreaudio.so $Frameworks
	cp /usr/local/bin/jackd $APPROOT/MacOS
	JACK_SHARED_OBJECTS="$Frameworks/*.so"
    fi
fi

# copy locale files
if test x$WITH_NLS != x ; then
    echo "NLS support ..."
    echo "I hope you remembered to run scons msgupdate!"
    LINGUAS=
    for file in ../../gtk2_ardour/*.mo 
    do
	lang=`basename $file | sed 's/\.mo//'`
	mkdir -p $Locale/$lang/LC_MESSAGES
	cp $file $Locale/$lang/LC_MESSAGES/gtk2_ardour.mo
	LINGUAS="$LINGUAS $lang"
    done
    for file in ../../libs/ardour/*.mo 
    do
	lang=`basename $file | sed 's/\.mo//'`
	mkdir -p $Locale/$lang/LC_MESSAGES
	cp $file $Locale/$lang/LC_MESSAGES/libardour.mo
    done
    for l in $LINGUAS
    do
      if [ -d $GTKSTACK_ROOT/share/locale/$l ] ; then
	  echo "Copying GTK i18n files for $l..."
	  cp -r $GTKSTACK_ROOT/share/locale/$l $Locale
      else
	  # try with just the language spec
	  just_lang=`echo $l | sed 's/_[A-Z][A-Z]$//'`
	  if [ -d $GTKSTACK_ROOT/share/locale/$just_lang ] ; then
	      echo "Copying GTK i18n files for $l..."
	      cp -r $GTKSTACK_ROOT/share/locale/$just_lang $Locale
	  fi
      fi
      if [ -d $ARDOURSTACK_ROOT/share/locale/$l ] ; then
	  echo "Copying ardour-dep i18n files for $l..."
	  cp -r $ARDOURSTACK_ROOT/share/locale/$l $Locale
      else
	  # try with just the language spec
	  just_lang=`echo $l | sed 's/_[A-Z][A-Z]$//'`
	  if [ -d $ARDOURSTACK_ROOT/share/locale/$just_lang ] ; then
	      echo "Copying ardour-dep i18n files for $l..."
	      cp -r $ARDOURSTACK_ROOT/share/locale/$just_lang $Locale
	  fi
      fi
    done
else
    echo "Skipping NLS support"
fi


#
# Copy stuff that may be dynamically loaded
# 

cp -R $GTKSTACK_ROOT/etc/* $Etc
echo "Copying all Pango modules ..."
cp -R $GTKSTACK_ROOT/lib/pango/1.6.0/modules/*.so $Frameworks/modules
echo "Copying all GDK Pixbuf loaders ..."
cp -R $GTKSTACK_ROOT/lib/gdk-pixbuf-2.0/2.10.0/loaders/*.so $Frameworks/modules
# charset alias file
cp -R $GTKSTACK_ROOT/lib/charset.alias $Resources

# generate new Pango module file
cat > pangorc <<EOF 
[Pango]
ModulesPath=$GTKSTACK_ROOT/lib/pango/1.6.0/modules
EOF
env PANGO_RC_FILE=pangorc $GTKSTACK_ROOT/bin/pango-querymodules | sed "s?$GTKSTACK_ROOT/lib/pango/1.6.0/modules/?@executable_path/../lib/modules/?" > $Resources/pango.modules
rm pangorc

# generate a new GDK pixbufs loaders file
gdk-pixbuf-query-loaders | sed "s?$GTKSTACK_ROOT/lib/gdk-pixbuf-2.0/2.10.0/loaders/?@executable_path/../lib/modules/?" > $Resources/gdk-pixbuf.loaders

# We rely on clearlooks, so include a version from our own build tree
# this one is special - we will set GTK_PATH to $Libraries/clearlooks

echo "Copying clearlooks ..."
cp $BUILD_ROOT/libs/clearlooks-newer/libclearlooks.dylib $Frameworks
# Copy over libpixmap for Calf plugins
cp $GTKSTACK_ROOT/lib/gtk-2.0/2.10.0/engines/libpixmap.so $Frameworks

# Symbolically Link them for GTK to find
mkdir -p $Frameworks/clearlooks/engines
(cd $Frameworks/clearlooks/engines && ln -s ../../libclearlooks.dylib libclearlooks.dylib && ln -s ../../libclearlooks.dylib libclearlooks.so)
(cd $Frameworks/clearlooks/engines && ln -s ../../libpixmap.so libpixmap.dylib && ln -s ../../libpixmap.so libpixmap.so)

# Copy over libreadline for Calf plugins
cp $GTKSTACK_ROOT/lib/libreadline.6.2.dylib $Frameworks

# Chmod libreadline to ensure writeability, needed for install_name_tool later
chmod +w $Frameworks/libreadline.6.2.dylib

if test x$WITH_LADSPA != x ; then
    if test x$SAE != x ; then
	plugdir=sae_ladspa
    elif test x$MIXBUS != x ; then
	plugdir=mixbus_ladspa
    else
	plugdir=ladspa
    fi
    if [ -d $plugdir -a "x$(ls $plugdir)" != x ] ; then 
        echo "Copying `ls $plugdir | wc -l` plugins ..."
        cp -r $plugdir/* $Plugins
    fi
fi

# Control Surface shared libraries
cp $BUILD_ROOT/libs/surfaces/*/libardour_*.dylib $Surfaces
mv $Surfaces/libardour_cp*.dylib $Frameworks

# VAMP plugins that we use
cp $BUILD_ROOT/libs/vamp-plugins/libardourvampplugins.dylib $Frameworks

# SUIL modules are all dynamically loaded, but on OS X there may or may not
# be any (as of November 2012, there are none for OS X)
if [ -d $ARDOURSTACKROOT/lib/suil-0 -a `ls $ARDOURSACK_ROOT/lib/suil-0/lib* 2>/dev/null | wc -l` -gt 0 ] ; then
    cp $ARDOURSTACK_ROOT/lib/suil-0/lib* $Frameworks
fi

while [ true ] ; do 
    missing=false
    for file in $APPROOT/MacOS/* $Frameworks/* $Frameworks/modules/* $Plugins/*.so ; do 
	if ! file $file | grep -qs Mach-O ; then
	    continue
	fi
	if test x$INTERNAL_JACK != x ; then
	    deps=`otool -L $file | awk '{print $1}' | egrep "($PGROOT|$PAROOT|$GTKSTACK_ROOT|$ARDOURSTACK_ROOT|/opt/|/local/|libs/)"`
	else
	    # do not include libjack
	    deps=`otool -L $file | awk '{print $1}' | egrep "($PGROOT|$PAROOT|$GTKSTACK_ROOT|$ARDOURSTACK_ROOT|/opt/|/local/|libs/)" | grep -v 'libjack\.'`
	fi
	echo -n "."
	for dep in $deps ; do
	    base=`basename $dep`
	    if ! test -f $Frameworks/$base; then
		if echo $dep | grep -sq '^libs' ; then
		    cp ../../$dep $Frameworks
		else
		    cp $dep $Frameworks
		fi
		missing=true
	    fi
	done
    done
    if test x$missing = xfalse ; then
	# everything has been found
	break
    fi
done
echo

echo "Copying other stuff to $APPDIR  ..."

cp ../../gtk2_ardour/*bindings  $Resources
cp ../../gtk2_ardour/ardour.menus $Resources
cp ../../gtk2_ardour/ardour-sae.menus $Resources
if test x$SAE != x ; then
    cp ../../ardour_system_sae.rc $Resources/ardour_system.rc
    echo cp ../../ardour_system_sae.rc $Resources/ardour_system.rc
    cp ../../instant.xml.sae $Resources/instant.xml
    echo cp ../../instant.xml.sae $Resources/instant.xml
else
#    cp ../../ardour_system.rc $Resources/ardour_system.rc
#    echo FOO cp ../../ardour_system.rc $Resources/ardour_system.rc
    cp ../../instant.xml $Resources/instant.xml
    echo cp ../../instant.xml $Resources/instant.xml
fi
cp ../../gtk2_ardour/ardour2_ui_sae.conf $Resources
cp ../../gtk2_ardour/ardour2_ui_default.conf $Resources
cp ../../gtk2_ardour/ardour2_ui_default.conf $Resources/ardour2_ui.conf
cp ../../gtk2_ardour/ardour2_ui_light.rc $Resources
cp ../../gtk2_ardour/ardour2_ui_dark.rc $Resources
cp ../../gtk2_ardour/ardour2_ui_light_sae.rc $Resources
cp ../../gtk2_ardour/ardour2_ui_dark_sae.rc $Resources

cp -r ../../gtk2_ardour/icons $Resources
cp -r ../../gtk2_ardour/pixmaps $Resources

#
# put sooper sekrit ingredients here and they will be copied
#

if [ -d specialSauce ] ; then
    cp -r specialSauce $Resources
fi

# share stuff

cp -R ../../gtk2_ardour/splash.png $Shared
cp ../../templates/*.template $Shared/templates/

# go through and recursively remove any .svn dirs in the bundle
for svndir in `find $APPDIR -name .svn -type dir`; do
    rm -rf $svndir
done

# now fix up the executables
echo "Fixing up executable dependency names ..."
executables=$MAIN_EXECUTABLE
if test x$INTERNAL_JACK != x ; then
    executables="$executables jackd"
fi
if test x$SAE != x ; then
    executables="$executables"
fi

for exe in $executables; do
    EXE=$APPROOT/MacOS/$exe
    changes=""
    if test x$INTERNAL_JACK != x ; then
	for lib in `otool -L $EXE | egrep "($GTKSTACK_ROOT|$ARDOURSTACK_ROOT|/opt/|/local/|libs/)" | awk '{print $1}'` ; do
	    base=`basename $lib`
	    changes="$changes -change $lib @executable_path/../lib/$base"
	done
    else
	for lib in `otool -L $EXE | egrep "($GTKSTACK_ROOT|$ARDOURSTACK_ROOT|/opt/|/local/|libs/)" | awk '{print $1}' | grep -v 'libjack\.'` ; do
	    base=`basename $lib`
	    changes="$changes -change $lib @executable_path/../lib/$base"
	done
    fi
    if test "x$changes" != "x" ; then
	install_name_tool $changes $EXE
    fi
done

echo "Fixing up library names ..."
# now do the same for all the libraries we include
for dylib in $JACK_SHARED_OBJECTS $Frameworks/*.dylib $Frameworks/modules/*.so $Surfaces/*.dylib ; do
    # skip symlinks
    if test ! -L $dylib ; then
	
	# change all the dependencies

	changes=""
	if test x$INTERNAL_JACK != x ; then
	    for lib in `otool -L $dylib | egrep "($GTKSTACK_ROOT|$ARDOURSTACK_ROOT|/opt/|/local/|libs/)" | awk '{print $1}'` ; do
		base=`basename $lib`
		changes="$changes -change $lib @executable_path/../lib/$base"
	    done
	else
	    for lib in `otool -L $dylib | egrep "($GTKSTACK_ROOT|$ARDOURSTACK_ROOT|/opt/|/local/|libs/)" | awk '{print $1}' | grep -v 'libjack\.'` ; do
		base=`basename $lib`
		changes="$changes -change $lib @executable_path/../lib/$base"
	    done
	fi

	if test "x$changes" != x ; then
	    if  install_name_tool $changes $dylib ; then
		:
	    else
		exit 1
	    fi
	fi

	# now the change what the library thinks its own name is

	base=`basename $dylib`
	install_name_tool -id @executable_path/../lib/$base $dylib
    fi
done

#
# and now ... the DMG
# 

rm -rf $PRODUCT_PKG_DIR
mkdir $PRODUCT_PKG_DIR

if [ x$SAE != x ] ; then
	
    # SAE packaging
    
    echo "Creating SAE packaging directory"
    mv $APPDIR $PRODUCT_PKG_DIR/Ardour2-SAE.app
    cp HowToInstallArdourSAE.pdf "$PRODUCT_PKG_DIR/How To Install Ardour SAE.pdf"
    cp SAE-de-keypad.pdf "$PRODUCT_PKG_DIR/Ardour SAE Shortcuts (keypad).pdf"
    cp SAE-de-nokeypad.pdf "$PRODUCT_PKG_DIR/Ardour SAE Shortcuts.pdf"
    
elif [ x$MIXBUS != x ] ; then

     # Mixbus packaging

    echo "Creating Mixbus packaging directory"
    mv $APPDIR $PRODUCT_PKG_DIR/
    cp MixBus_Install_QuickStart.pdf "$PRODUCT_PKG_DIR/Mixbus Install & Quick Start Guide.pdf"
   
else 

    echo "Creating $APPNAME packaging directory"
    mv $APPDIR $PRODUCT_PKG_DIR/

fi

#echo bzipping ...
#ZIPFILE=$APPNAME-${release_version}-${svn_version}.bz2
#tar cpf - $PRODUCT_PKG_DIR | bzip2 > $ZIPFILE

#echo "Building DMG ..."

UC_DMG=$APPNAME-${release_version}-${svn_version}.dmg

rm -f $UC_DMG
echo hdiutil create $UC_DMG -volname $APPNAME-${release_version} -fs HFS+ -srcfolder $PRODUCT_PKG_DIR
hdiutil create $UC_DMG -volname $APPNAME-${release_version} -fs HFS+ -srcfolder $PRODUCT_PKG_DIR

# compress it
#echo "Compressing DMG ..."
#rm -f $FINAL_DMG
#hdiutil convert $UC_DMG -format UDBZ -o $FINAL_DMG

echo "Done."

