#!/bin/sh

set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
APP_NAME="CrossSubtitle-AI"
VERSION=$(node -p "require('$ROOT_DIR/package.json').version")
ARCH=$(uname -m)
APP_PATH="$ROOT_DIR/src-tauri/target/release/bundle/macos/$APP_NAME.app"
DMG_DIR="$ROOT_DIR/src-tauri/target/release/bundle/dmg"
DMG_PATH="$DMG_DIR/${APP_NAME}_${VERSION}_${ARCH}.dmg"
STAGING_DIR=$(mktemp -d "${TMPDIR:-/tmp}/crosssubtitle-dmg.XXXXXX")

cleanup() {
  rm -rf "$STAGING_DIR"
}

trap cleanup EXIT

cd "$ROOT_DIR"
npm run tauri-build-app

mkdir -p "$DMG_DIR"
rm -f "$DMG_PATH"
ditto "$APP_PATH" "$STAGING_DIR/$APP_NAME.app"
ln -s /Applications "$STAGING_DIR/Applications"

hdiutil create \
  -volname "$APP_NAME" \
  -srcfolder "$STAGING_DIR" \
  -ov \
  -format UDZO \
  "$DMG_PATH"

printf 'DMG created: %s\n' "$DMG_PATH"
