#!/usr/bin/env bash

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"
source "$REPO_ROOT/scripts/version-common.sh"

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "error: this script must run on macOS" >&2
  exit 1
fi

SKIP_BUILD=0
for arg in "$@"; do
  case "$arg" in
    --no-build) SKIP_BUILD=1 ;;
    -h|--help) sed -n '2,13p' "$0"; exit 0 ;;
    *) echo "error: unknown arg: $arg" >&2; exit 2 ;;
  esac
done

VERSION="$(smplayer_current_version macos)"

APP_DISPLAY_NAME="smPlayer"
VOL_NAME="$APP_DISPLAY_NAME"
DMG_NAME="${APP_DISPLAY_NAME}-${VERSION}-macos.dmg"
APP_SRC="build/macos/Build/Products/Release/sm_emby.app"
DIST_DIR="dist"
DMG_PATH="${DIST_DIR}/${DMG_NAME}"

if [[ "$SKIP_BUILD" -eq 0 ]]; then
  BUILD_ARGS=(build macos --release)
  if ! smplayer_has_flutter_option --build-name "${BUILD_ARGS[@]}"; then
    BUILD_ARGS+=(--build-name "$VERSION")
  fi
  if ! smplayer_has_dart_define SMPLAYER_VERSION "${BUILD_ARGS[@]}"; then
    BUILD_ARGS+=("--dart-define=SMPLAYER_VERSION=$VERSION")
  fi

  echo "==> flutter ${BUILD_ARGS[*]}"
  flutter "${BUILD_ARGS[@]}"
fi

if [[ ! -d "$APP_SRC" ]]; then
  echo "error: app bundle not found at $APP_SRC" >&2
  echo "       run without --no-build, or build first: flutter build macos --release" >&2
  exit 1
fi

STAGE_DIR="$(mktemp -d -t smemby-dmg)"
cleanup() {
  if [[ -n "${MOUNTED_DEV:-}" ]] && hdiutil info | grep -q "$MOUNTED_DEV"; then
    hdiutil detach "$MOUNTED_DEV" -quiet || true
  fi
  rm -rf "$STAGE_DIR"
}
trap cleanup EXIT

echo "==> staging .app at $STAGE_DIR"
mkdir -p "$STAGE_DIR/dmg"
cp -R "$APP_SRC" "$STAGE_DIR/dmg/${APP_DISPLAY_NAME}.app"
ln -s /Applications "$STAGE_DIR/dmg/Applications"

mkdir -p "$DIST_DIR"
rm -f "$DMG_PATH"

echo "==> hdiutil create $DMG_PATH"
hdiutil create \
  -volname "$VOL_NAME" \
  -srcfolder "$STAGE_DIR/dmg" \
  -ov -format UDZO \
  "$DMG_PATH" >/dev/null

echo "==> verifying DMG mounts"
ATTACH_OUT="$(LANG=C LC_ALL=C hdiutil attach "$DMG_PATH" -nobrowse -readonly -noautoopen)"
MOUNTED_DEV="$(printf '%s\n' "$ATTACH_OUT" | awk '/^\/dev\//{print $1; exit}')"
MOUNT_POINT="$(printf '%s\n' "$ATTACH_OUT" | awk -F'\t' '/\/Volumes\//{print $NF; exit}')"

if [[ -z "$MOUNTED_DEV" || -z "$MOUNT_POINT" ]]; then
  echo "error: failed to parse hdiutil attach output" >&2
  echo "$ATTACH_OUT" >&2
  exit 1
fi

if [[ ! -d "$MOUNT_POINT/${APP_DISPLAY_NAME}.app" ]] || [[ ! -L "$MOUNT_POINT/Applications" ]]; then
  echo "error: DMG layout verification failed (missing app or Applications symlink)" >&2
  hdiutil detach "$MOUNTED_DEV" -quiet || true
  exit 1
fi
hdiutil detach "$MOUNTED_DEV" -quiet
MOUNTED_DEV=""

SIZE_HUMAN="$(du -h "$DMG_PATH" | awk '{print $1}')"
echo
echo "✓ DMG ready: $DMG_PATH ($SIZE_HUMAN)"
echo "  Unsigned: first launch on another Mac requires right-click -> Open."
