#!/bin/bash
set -e
set -x

[ "$KEEP_BUNDLE" = "" ] || exit 0
[ "$SKIP_GUI_O_MAC_TIC" = "" ] || exit 0

# Clean up...
rm -rf "$BUILD_DIR/gui-o-mac-tic"
if [ "$GUI_O_MAC_TIC_REPO" = "" ]; then
    cp -va $SOURCE_DIR/submodules/gui-o-mac-tic $BUILD_DIR/gui-o-mac-tic
else
    git clone --recursive -b "$GUI_O_MAC_TIC_BRANCH" \
        "$GUI_O_MAC_TIC_REPO" "$BUILD_DIR/gui-o-mac-tic"
fi

# Build GUI-o-Mac-tic
cd $BUILD_DIR/gui-o-mac-tic
rm -f src/Assets.xcassets/AppIcon.appiconset/Icon-*.png
mv $ICONSET_DIR/* src/Assets.xcassets/AppIcon.appiconset/
rmdir $ICONSET_DIR

cp "$SOURCE_DIR/packages/macos/configurator.sh" \
  "$BUILD_DIR/gui-o-mac-tic/share/configurator.sh"

perl -pi -e "s/32325SM62E/$DMG_SIGNING_IDENTITY/g" \
	"$BUILD_DIR/gui-o-mac-tic/GUI-o-Mac-tic.xcodeproj/project.pbxproj"
xcodebuild -project "$BUILD_DIR/gui-o-mac-tic/GUI-o-Mac-tic.xcodeproj" \
	EXECUTABLE_NAME=Mailpile \
	PRODUCT_BUNDLE_IDENTIFIER=is.mailpile.gui-o-mac-tic.mailpile \
	PRODUCT_MODULE_NAME=Mailpile \
	PRODUCT_NAME=Mailpile \
	PROJECT_NAME=Mailpile \
	WRAPPER_NAME=Mailpile.app

# This dance gives us a fresh new Mailpile.app, but keeps the old homebrew
# setup, if one exists.
if [ -e "$MAILPILE_BREW_ROOT" ]; then
    rm -rf $BUILD_DIR/last_brew
    mv "$MAILPILE_BREW_ROOT" "$BUILD_DIR/last_brew"
fi
mkdir -p "$BUILD_DIR/last_brew"
rm -rf "$BUILD_DIR/Mailpile.app"
mv "$BUILD_DIR/gui-o-mac-tic/build/Release/Mailpile.app" "$BUILD_DIR/"
mv "$BUILD_DIR/last_brew" "$MAILPILE_BREW_ROOT"

# Cleanup
rm -rf "$BUILD_DIR/gui-o-mac-tic"

#############################################
# xcodebuild argument that might be useful. #
#############################################
#
#Asset Catalog App Icon Set Name (ASSETCATALOG_COMPILER_APPICON_NAME) - Name of an asset catalog app icon set whose contents will be merged into the Info.plist.
#Development Team (DEVELOPMENT_TEAM) - The team ID of a development team to use for signing certificates and provisioning profiles.
#macOS Deployment Target (MACOSX_DEPLOYMENT_TARGET) - Code will load on this and later versions of macOS. Framework APIs that are unavailable in earlier versions will be weak-linked; your code should check for null function pointers or specific system versions before calling newer APIs.
#Product Module Name (PRODUCT_MODULE_NAME) - The name to use for the source code module constructed for this target, and which will be used to import the module in implementation source files. Must be a valid identifier.
#Product Name (PRODUCT_NAME) - This is the basename of the product generated by the target.
#Project Name (PROJECT_NAME) - The name of the current project.
#WRAPPER_NAME - Specifies the filename, including the appropriate extension, of the product bundle.
#

