#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DESKTOP_DIR="$ROOT_DIR/desktop"
TAURI_DIR="$DESKTOP_DIR/src-tauri"
APP_PATH=""
SIGN_IDENTITY=""
NOTARIZE=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --app)
      APP_PATH="${2:-}"
      shift 2
      ;;
    --sign)
      SIGN_IDENTITY="${2:-}"
      shift 2
      ;;
    --notarize)
      NOTARIZE=1
      shift
      ;;
    -h|--help)
      echo "usage: scripts/create-desktop-dmg.sh [--app PATH] [--sign IDENTITY] [--notarize]"
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      exit 2
      ;;
  esac
done

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "DMG packaging is macOS-only" >&2
  exit 2
fi

if [[ -z "$APP_PATH" ]]; then
  APP_PATH="$(find "$TAURI_DIR/target" -path "*/release/bundle/macos/*.app" -maxdepth 8 -print 2>/dev/null | sort | tail -n 1)"
fi

if [[ -z "$APP_PATH" || ! -d "$APP_PATH" ]]; then
  echo "could not find a built .app bundle" >&2
  exit 1
fi

read_config() {
  local expr="$1"
  node -e "const c=require('$TAURI_DIR/tauri.conf.json'); console.log($expr)" 2>/dev/null
}

PRODUCT_NAME="$(read_config 'c.productName || "Rho"')"
VERSION="$(read_config 'c.version || "0.1.0"')"
case "${TAURI_TARGET:-$(uname -m)}" in
  aarch64-apple-darwin|arm64) ARCH="aarch64" ;;
  x86_64-apple-darwin|x86_64) ARCH="x64" ;;
  *) ARCH="$(uname -m)" ;;
esac

BUNDLE_ROOT="$(dirname "$(dirname "$APP_PATH")")"
DMG_DIR="$BUNDLE_ROOT/dmg"
DMG_PATH="$DMG_DIR/${PRODUCT_NAME}_${VERSION}_${ARCH}.dmg"
STAGE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/rho-dmg.XXXXXX")"

cleanup() {
  rm -rf "$STAGE_DIR"
}
trap cleanup EXIT

mkdir -p "$DMG_DIR"
cp -R "$APP_PATH" "$STAGE_DIR/"
ln -s /Applications "$STAGE_DIR/Applications"

STAGED_APP="$STAGE_DIR/$(basename "$APP_PATH")"
if [[ -n "$SIGN_IDENTITY" ]]; then
  codesign --force --deep --options runtime --timestamp \
    --entitlements "$TAURI_DIR/Entitlements.plist" \
    --sign "$SIGN_IDENTITY" "$STAGED_APP"
fi

rm -f "$DMG_PATH"
hdiutil create -volname "$PRODUCT_NAME" -srcfolder "$STAGE_DIR" -ov -format UDZO "$DMG_PATH"

if [[ -n "$SIGN_IDENTITY" ]]; then
  codesign --force --timestamp --sign "$SIGN_IDENTITY" "$DMG_PATH"
fi

if [[ "$NOTARIZE" == "1" ]]; then
  : "${APPLE_ID:?APPLE_ID is required for notarization}"
  : "${APPLE_PASSWORD:?APPLE_PASSWORD is required for notarization}"
  : "${APPLE_TEAM_ID:?APPLE_TEAM_ID is required for notarization}"
  xcrun notarytool submit "$DMG_PATH" \
    --apple-id "$APPLE_ID" \
    --password "$APPLE_PASSWORD" \
    --team-id "$APPLE_TEAM_ID" \
    --wait
  xcrun stapler staple "$DMG_PATH"
fi

echo "$DMG_PATH"
