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

# Create a distributable DMG for the macOS Spacetris app
# Usage: ./scripts/create-dmg.sh <app-bundle-path> <output-dmg>
# Example: ./scripts/create-dmg.sh dist/SpacetrisGame-mac/spacetris.app dist/SpacetrisGame.dmg

if [[ $# -lt 2 ]]; then
    echo "Usage: $0 <app-bundle-path> <output-dmg>"
    echo "Example: $0 dist/SpacetrisGame-mac/spacetris.app dist/SpacetrisGame.dmg"
    exit 1
fi

APP_BUNDLE="$1"
OUTPUT_DMG="$2"

if [[ ! -d "$APP_BUNDLE" ]]; then
    echo "Error: App bundle not found at $APP_BUNDLE" >&2
    exit 1
fi

if [[ ! "$APP_BUNDLE" =~ \.app$ ]]; then
    echo "Error: First argument must be a .app bundle" >&2
    exit 1
fi

# Remove existing DMG if present
rm -f "$OUTPUT_DMG"

APP_NAME=$(basename "$APP_BUNDLE" .app)
VOLUME_NAME="$APP_NAME"
TEMP_DMG="${OUTPUT_DMG%.dmg}-temp.dmg"

echo "[create-dmg] Creating temporary DMG..."
# Create a temporary read-write DMG (generous size to fit the app + padding)
hdiutil create -size 200m -fs HFS+ -volname "$VOLUME_NAME" "$TEMP_DMG"

echo "[create-dmg] Mounting temporary DMG..."
MOUNT_DIR=$(hdiutil attach "$TEMP_DMG" -nobrowse | grep "/Volumes/$VOLUME_NAME" | awk '{print $3}')

if [[ -z "$MOUNT_DIR" ]]; then
    echo "Error: Failed to mount temporary DMG" >&2
    exit 1
fi

echo "[create-dmg] Copying app bundle to DMG..."
cp -R "$APP_BUNDLE" "$MOUNT_DIR/"

# Create Applications symlink for drag-and-drop installation
echo "[create-dmg] Creating Applications symlink..."
ln -s /Applications "$MOUNT_DIR/Applications"

# Set custom icon if available
VOLUME_ICON="$APP_BUNDLE/Contents/Resources/AppIcon.icns"
if [[ -f "$VOLUME_ICON" ]]; then
    echo "[create-dmg] Setting custom volume icon..."
    cp "$VOLUME_ICON" "$MOUNT_DIR/.VolumeIcon.icns"
    SetFile -c icnC "$MOUNT_DIR/.VolumeIcon.icns" 2>/dev/null || true
fi

# Unmount
echo "[create-dmg] Ejecting temporary DMG..."
hdiutil detach "$MOUNT_DIR"

# Convert to compressed read-only DMG
echo "[create-dmg] Converting to compressed DMG..."
hdiutil convert "$TEMP_DMG" -format UDZO -o "$OUTPUT_DMG"

# Cleanup
rm -f "$TEMP_DMG"

echo "[create-dmg] Created: $OUTPUT_DMG"
