#!/bin/bash

MACOS_SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd "${MACOS_SCRIPT_DIR}" || exit 1

PYTHON="python3"
LIGHT="${LIGHT:=0}"
if [ "${CLIENT_ONLY}" == "1" ]; then
  LIGHT="1"
fi
if [ "${LIGHT}" == "1" ]; then
  APP_NAME="Xpra-Light"
else
  APP_NAME="Xpra"
fi
APP_DIR="image/${APP_NAME}.app"

echo
echo
echo "*******************************************************************************"
if [ ! -d "${APP_DIR}" ]; then
	echo "${APP_DIR} is missing!"
	echo "run make-app.sh first"
	exit 1
fi

#get the version and build info from the python build records:
export PYTHONPATH="${APP_DIR}/Contents/Frameworks/python/"
VERSION=$(${PYTHON} -c "from xpra import __version__;import sys;sys.stdout.write(__version__)")
REVISION=$(${PYTHON} -c "from xpra import src_info;import sys;sys.stdout.write(str(src_info.REVISION))")
REV_MOD=$(${PYTHON} -c "from xpra import src_info;import sys;sys.stdout.write(['','M'][src_info.LOCAL_MODIFICATIONS>0])")
BUILD_INFO="${BUILD_INFO}-$(uname -m)"
DMG_NAME="${APP_NAME}${BUILD_INFO}-${VERSION}-r${REVISION}${REV_MOD}.dmg"

echo "Creating $DMG_NAME"

rm -fr image/Blank.*
rm -fr image/*dmg

echo "Mounting blank DMG"
mkdir -p "image/Blank"
cp "Blank.dmg.bz2" "image/"
bunzip2 "image/Blank.dmg.bz2"
hdiutil mount "image/Blank.dmg" -mountpoint "./image/Blank"

echo "Copying app into the DMG"
ditto "${APP_DIR}" "./image/Blank/${APP_NAME}.app"
chmod -Rf go-w "image/Blank/"*
hdiutil detach "image/Blank"

echo "Creating compressed DMG"
hdiutil convert "image/Blank.dmg" -format UDBZ -o "image/${DMG_NAME}"

if [ ! -z "${CODESIGN_KEYNAME}" ]; then
		echo "Signing with key '${CODESIGN_KEYNAME}'"
		codesign --deep --force --verify --verbose --sign "${CODESIGN_KEYNAME}" "image/${DMG_NAME}"
else
		echo "DMG Signing skipped (no keyname)"
fi

echo "Copying $DMG_NAME to the desktop"
ditto "image/${DMG_NAME}" "${HOME}/Desktop/"
echo "Size of disk image: $(du -sh "image/$DMG_NAME")"

echo "Done DMG"
echo "*******************************************************************************"
echo
