#!/bin/zsh
rm -rf dist
rm -rf bin
rm -rf obj
rm -rf *.dmg

dotnet publish -r osx-x64 --self-contained true -p:PublishSingleFile=true -p:EnableCompressionInSingleFile=true
dotnet publish -r osx-arm64 --self-contained true -p:PublishSingleFile=true -p:EnableCompressionInSingleFile=true

INTEL_PUBLISH="bin/Release/net8.0/osx-x64/publish"
ARM64_PUBLISH="bin/Release/net8.0/osx-arm64/publish"
APP_ROOT="dist/SplatTool.app"

mkdir -p "$APP_ROOT/Contents/MacOS"
mkdir -p "$APP_ROOT/Contents/Resources"
mkdir -p "$APP_ROOT/Contents/Frameworks"

SHORT_SHA="$(git rev-parse --short HEAD)"
VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" assets/Info.plist)

cp assets/Info.plist "$APP_ROOT/Contents/"
cp assets/icon.icns "$APP_ROOT/Contents/Resources/"
cp assets/config.json "$APP_ROOT/Contents/Resources"
cp -r modmenu "$APP_ROOT/Contents/Resources/"
cp icon.ico "$APP_ROOT/Contents/Resources/"
cp assets/root_helper/root_helper "$APP_ROOT/Contents/MacOS"
cp "$ARM64_PUBLISH/Photino.Native.dylib" "$APP_ROOT/Contents/Frameworks"
lipo -create -output "$APP_ROOT/Contents/MacOS/SplatTool" "$INTEL_PUBLISH/SplatTool" "$ARM64_PUBLISH/SplatTool"
lipo -create -output "$APP_ROOT/Contents/Frameworks/libnfd.dylib" "$INTEL_PUBLISH/libnfd.dylib" "$ARM64_PUBLISH/libnfd.dylib"

install_name_tool -add_rpath "@loader_path/../Frameworks" "$APP_ROOT/Contents/MacOS/SplatTool"
install_name_tool -id "@rpath/libnfd.dylib" "$APP_ROOT/Contents/Frameworks/libnfd.dylib"
install_name_tool -id "@rpath/Photino.Native.dylib" "$APP_ROOT/Contents/Frameworks/Photino.Native.dylib"

xattr -cr "$APP_ROOT"

chmod +x "$APP_ROOT/Contents/MacOS/SplatTool"
chmod +x "$APP_ROOT/Contents/MacOS/root_helper"

codesign --remove-signature "$APP_ROOT"
codesign --sign "-" --entitlements assets/entitlements.plist --force --deep --preserve-metadata=entitlements,requirements,flags,runtime --timestamp "$APP_ROOT"
codesign -d --entitlements - "$APP_ROOT/Contents/MacOS/SplatTool"
codesign -vvv --deep --strict "$APP_ROOT"

ln -sf "/Applications" "dist/Applications"
hdiutil create -format UDZO -fs HFS+ -ov -volname "SplatTool" -srcfolder dist/ SplatTool-$VERSION-$SHORT_SHA-Universal-OSX.dmg