#!/usr/bin/env bash

APP=$1
VERSION=$2

CODESIGNID="Developer ID Application: Selim Mustafaev"
NOTARY="--username selim@fastmail.fm --password actd-lhgc-kooe-jtrs"
APPNAME="AutoCat"
BUNDLEID="pro.aliencat.AutoCat"

function msg {
	printf "\\n${fBold}-- %s${fNormal}\\n" "${@}"
}

srcDir="$(mktemp -dt $$)"

msg "Preparing disk image sources at ${srcDir}:"
cp -R "${APP}" "${srcDir}"
ln -s /Applications "${srcDir}"

# Disk image name
dmg_name="${APPNAME}-${VERSION}"

msg "Creating disk image:"
hdiutil create -format UDBZ -fs HFS+ -srcdir "${srcDir}" -volname "${dmg_name}" "${dmg_name}.dmg"

# Sign disk image
codesign --deep --force -v -s "${CODESIGNID}" --timestamp "${dmg_name}.dmg"

# Notarize the dmg
if ! test -z "$NOTARY" ; then
	zip "${dmg_name}.dmg.zip" "${dmg_name}.dmg"
	uuid=`xcrun altool --notarize-app --primary-bundle-id "${BUNDLEID}" ${NOTARY} --file "${dmg_name}.dmg.zip" 2>&1 | grep 'RequestUUID' | awk '{ print $3 }'`
	echo "dmg Result= $uuid" # Display identifier string
	sleep 15
	while :
	do
		fullstatus=`xcrun altool --notarization-info "$uuid" ${NOTARY} 2>&1`  # get the status
		status1=`echo "$fullstatus" | grep 'Status\:' | awk '{ print $2 }'`
		if [ "$status1" = "success" ]; then
			xcrun stapler staple "${dmg_name}.dmg"   #  staple the ticket
			xcrun stapler validate -v "${dmg_name}.dmg"
			echo "dmg Notarization success"
			break
		elif [ "$status1" = "in" ]; then
			echo "dmg Notarization still in progress, sleeping for 15 seconds and trying again"
			sleep 15
		else
			echo "dmg Notarization failed fullstatus below"
			echo "$fullstatus"
		exit 1
		fi
	done
fi

# Zip disk image for redistribution
#zip "${dmg_name}.zip" "${dmg_name}.dmg"
#rm "${dmg_name}.dmg"

msg "Removing disk image caches:"
rm -rf "${srcDir}"
rm "${dmg_name}.dmg.zip"