#!/bin/sh

set -u
set -e

SRCDIR=@CMAKE_SOURCE_DIR@
BINDIR=@CMAKE_BINARY_DIR@
CMAKE_COMMAND=@CMAKE_COMMAND@
INCLUDEJRE=@TVNC_INCLUDEJRE@
CPU_TYPE=@CPU_TYPE@

umask 022
APP="@CMAKE_PROJECT_NAME@ Viewer.app"
MACOS_APP_CERT_NAME="@MACOS_APP_CERT_NAME@"
MACOS_INST_CERT_NAME="@MACOS_INST_CERT_NAME@"

if [ -d "$APP" ]; then
	rm -rf "$APP"
fi

mkdir -p "$APP/Contents/MacOS"
mkdir -p "$APP/Contents/Resources/Java"
mkdir -p "$APP/Contents/Resources/Native"

if [ "$INCLUDEJRE" = "1" ]; then
	$CMAKE_COMMAND -DJRE_OUTPUT_DIR="$APP/Contents/PlugIns/jre/Contents/Home" \
		-P $BINDIR/java/cmake/BuildJRE.cmake
fi

install -m 644 pkgscripts/Info.plist "$APP/Contents/Info.plist"
if [ "$CPU_TYPE" = "x86_64" ]; then
	install -m 755 $SRCDIR/unix/vncviewer/JavaAppLauncher "$APP/Contents/MacOS/@CMAKE_PROJECT_NAME@ Viewer"
else
	install -m 755 bin/JavaAppLauncher "$APP/Contents/MacOS/@CMAKE_PROJECT_NAME@ Viewer"
fi
echo "APPL????" >"$APP/Contents/PkgInfo"
install -m 644 java/VncViewer.jar "$APP/Contents/Resources/Java/"
install -m 644 $SRCDIR/java/com/turbovnc/vncviewer/README.md "$APP/Contents/Resources/Java/"
install -m 644 $SRCDIR/LICENSE.txt "$APP/Contents/Resources/Java/"
install -m 644 $SRCDIR/release/turbovnc.icns "$APP/Contents/Resources/"
install -m 644 $SRCDIR/release/vncviewer.icns "$APP/Contents/Resources/"
install -m 755 java/libturbovnchelper.dylib "$APP/Contents/Resources/Native/"

if [ "$MACOS_APP_CERT_NAME" != "" ]; then
	if [ "$INCLUDEJRE" = "1" ]; then
		# codesign assumes that directories with dots are frameworks, so we have to
		# rename those directories in the JRE.  Fortunately, all they contain is
		# license documents.
		pushd "$APP/Contents/Plugins/jre/Contents/Home/legal/"
		for dir in *; do
			mv "$dir" "`echo $dir | sed 's/\./_/g'`"
		done
		# We also need to temporarily make the license documents writeable.
		find . -perm 444 -print | while read file; do
			chmod 644 "$file"
		done
		popd
	fi
	codesign --deep -s "$MACOS_APP_CERT_NAME" --timestamp "$APP"
	if [ "$INCLUDEJRE" = "1" ]; then
		# Re-apply read-only permissions to the license documents
		pushd "$APP/Contents/Plugins/jre/Contents/Home/legal/"
		find . -perm 644 -print | while read file; do
			chmod 444 "$file"
		done
		popd
	fi
	codesign --deep -vv "$APP"
fi

exit
