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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

find_latest_app_bundle() {
  local candidate

  candidate="$(find "$ROOT_DIR/dist-mac" -type d -name "*.app" 2>/dev/null | sort | tail -n 1 || true)"
  if [[ -n "$candidate" ]]; then
    echo "$candidate"
    return 0
  fi

  candidate="$(find "$ROOT_DIR/dist-standalone" -type d -name "*.app" 2>/dev/null | sort | tail -n 1 || true)"
  if [[ -n "$candidate" ]]; then
    echo "$candidate"
    return 0
  fi

  candidate="$(find "$ROOT_DIR" -maxdepth 1 -type d -name "*.app" | sort | head -n 1 || true)"
  if [[ -n "$candidate" ]]; then
    echo "$candidate"
    return 0
  fi

  return 1
}

APP_BUNDLE="${APP_BUNDLE_PATH:-}"
if [[ -z "$APP_BUNDLE" ]]; then
  APP_BUNDLE="$(find_latest_app_bundle || true)"
fi

if ! command -v create-dmg >/dev/null 2>&1; then
  echo "create-dmg not found. Install with: brew install create-dmg" >&2
  exit 1
fi

if [[ ! -d "$APP_BUNDLE" ]]; then
  echo "App bundle not found." >&2
  echo "Set APP_BUNDLE_PATH to a built .app bundle or build one first." >&2
  exit 1
fi

APP_FILENAME="$(basename "$APP_BUNDLE")"
APP_NAME="${APP_FILENAME%.app}"
TS="$(date +%Y%m%d-%H%M%S)"
BUILD_DIR="${BUILD_DIR:-$ROOT_DIR/build}"
DMG_DIR="${DMG_DIR:-$BUILD_DIR/dmg}"
STAGE_DIR="$DMG_DIR/stage/$TS"
OUT_DMG="$DMG_DIR/${APP_NAME}-$TS.dmg"

mkdir -p "$DMG_DIR" "$STAGE_DIR"
cp -R "$APP_BUNDLE" "$STAGE_DIR/"

create-dmg \
  --volname "${APP_NAME} Installer" \
  --window-size 600 400 \
  --icon-size 120 \
  --icon "$APP_FILENAME" 175 190 \
  --icon "Applications" 425 190 \
  --hide-extension "$APP_FILENAME" \
  --app-drop-link 425 190 \
  "$OUT_DMG" \
  "$STAGE_DIR"

rm -rf "$STAGE_DIR"
rmdir "$DMG_DIR/stage" 2>/dev/null || true

echo "Created installer: $OUT_DMG"
