#!/bin/bash -e

echo "Creating macOS universal app bundle"
# create app skeleton
mkdir OpenRCT2-universal.app
mkdir OpenRCT2-universal.app/Contents

# copy all resources (most will overwrite)
mkdir OpenRCT2-universal.app/Contents/Resources
# Note: g2.dat is expected to only be in one (matching OS of build machine)
rsync -ah x64/OpenRCT2.app/Contents/Resources/* OpenRCT2-universal.app/Contents/Resources/
rsync -ah arm64/OpenRCT2.app/Contents/Resources/* OpenRCT2-universal.app/Contents/Resources/

# create a universal binary
mkdir OpenRCT2-universal.app/Contents/MacOS
lipo -create x64/OpenRCT2.app/Contents/MacOS/OpenRCT2 arm64/OpenRCT2.app/Contents/MacOS/OpenRCT2 -output OpenRCT2-universal.app/Contents/MacOS/OpenRCT2

# copy frameworks
mkdir OpenRCT2-universal.app/Contents/Frameworks
# with the exception of libopenrct2.dylib, the Frameworks are identical and are already universal dylibs
rsync -ah --exclude 'libopenrct2.dylib' x64/OpenRCT2.app/Contents/Frameworks/* OpenRCT2-universal.app/Contents/Frameworks
lipo -create x64/OpenRCT2.app/Contents/Frameworks/libopenrct2.dylib arm64/OpenRCT2.app/Contents/Frameworks/libopenrct2.dylib -output OpenRCT2-universal.app/Contents/Frameworks/libopenrct2.dylib

# handle Info.plist
defaults import $PWD/OpenRCT2-universal.app/Contents/Info $PWD/x64/OpenRCT2.app/Contents/Info.plist $PWD/arm64/OpenRCT2.app/Contents/Info.plist
arm64_min_ver=$(defaults read $PWD/arm64/OpenRCT2.app/Contents/Info LSMinimumSystemVersion)
x64_min_ver=$(defaults read $PWD/x64/OpenRCT2.app/Contents/Info LSMinimumSystemVersion)
defaults write $PWD/OpenRCT2-universal.app/Contents/Info LSMinimumSystemVersionByArchitecture -dict x86_64 ${x64_min_ver} arm64 ${arm64_min_ver}
