#!/bin/sh
set -eu
CONTENTS=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SOURCE="$CONTENTS/Resources/game"
DATA="$HOME/Library/Application Support/PortableIslands"
build(){ sed -n 's/.*"build"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$1" 2>/dev/null | head -n 1; }
mkdir -p "$DATA/app"
cp -f "$SOURCE/client.properties" "$DATA/client.properties"
cp -f "$SOURCE/app/portable-islands-launcher.jar" "$DATA/app/portable-islands-launcher.jar"
bundled=$(build "$SOURCE/app/release-build.json")
installed=$(build "$DATA/app/release-build.json")
# A newer build from the updater stays; the same build number can still mean a rebuilt package.
if [ ! -f "$DATA/app/client-desktop-0.1.0-SNAPSHOT.jar" ] || [ "${installed:-0}" -lt "${bundled:-0}" ] || { [ "${installed:-0}" -eq "${bundled:-0}" ] && ! cmp -s "$SOURCE/app/client-desktop-0.1.0-SNAPSHOT.jar" "$DATA/app/client-desktop-0.1.0-SNAPSHOT.jar"; }; then
 cp -f "$SOURCE/app/client-desktop-0.1.0-SNAPSHOT.jar" "$DATA/app/client-desktop-0.1.0-SNAPSHOT.jar"
 cp -f "$SOURCE/app/release-build.json" "$DATA/app/release-build.json"
fi
exec "$CONTENTS/runtime/bin/java" --enable-native-access=ALL-UNNAMED -Xdock:name="Portable Islands" -Xdock:icon="$CONTENTS/Resources/PortableIslands.icns" -jar "$DATA/app/portable-islands-launcher.jar" "$@"
