#!/bin/bash
# When you run this program, it will create an installer for mac.
#
# Make sure you also have XCode installed before running this script,
# otherwise yudit may not compile.
#
# Gaspar Sinai <gaspar@yudit.org> Tokyo 2020-05-10
#
APPNAME=Yudit
APPVERSION="3.0.8"

BUILD_NAME="unsigned"
if [ -f addon/yudit_sedy/yudit_sedy.h ]
then
BUILD_NAME="sedy"
fi

check_error () {
    echo "error: $2" >&2
    exit 1
} 

#make distclean
rm -rf target

# Make a proper unsigned app.
rm -rf ./macos/Yudit.app
cp -R ./macos/Yudit.app.signed ./macos/Yudit.app
rm -rf ./macos/Yudit.app/Contents/_CodeSignature

export DESTDIR="$(pwd)/target"
export PREFIX="/Applications/${APPNAME}.app/Contents/MacOS"
export MACOSDIR="${DESTDIR}/${PREFIX}"

mkdir -p $DESTDIR/Applications || check_error $? "Failed to create $DESTDIR/Applications/"
ln -s /Applications/ $DESTDIR/Applications/Applications || check_error $? "Failed to create symlink"
cp -R ./macos/Yudit.app $DESTDIR/Applications/ || check_error $? "Failed to copy to $DESTDIR/Applicaions/Yudit.app"

./configure --prefix=${PREFIX} || check_error $? "configure failed."
make -j 16 || check_error $? "make failed."
# uses DESTDIR
make install || check_error $? "make install failed."
# play safe if DESTDIR is / just move

cp $MACOSDIR/bin/yudit $MACOSDIR/Yudit

cp -R ./macos/dot_background $DESTDIR/Applications/.background || check_error $? "Failed to copy installer background"
# Resources and icons are in the bundle macos/Yudit.app bundle

#cp COPYING.TXT  $DESTDIR || check_error $? "can not copy COPYING.TXT"
echo "creating package"
hdiutil create -volname Yudit -srcfolder $DESTDIR/Applications/ -ov -format UDZO ./target/yudit-${APPVERSION}.x86_64-${BUILD_NAME}.dmg ||check_error $? "Failed to create disk image."

# codesign --force --sign "Developer ID Application: <identityIdentifier>" ./target/yudit-${APPVERSION}-${BUILD_NAME}.x86_64.dmg

echo "Your disk image is: target/yudit-${APPVERSION}.x86_64-${BUILD_NAME}.dmg"
