#!/bin/bash
set -e

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="$PROJECT_DIR/.build/release"
APP_NAME="FloatingMonitor"
APP_BUNDLE="$PROJECT_DIR/$APP_NAME.app"
DMG_NAME="$PROJECT_DIR/$APP_NAME.dmg"
STAGING="$PROJECT_DIR/dmg_staging"

echo "📦 构建 DMG: $DMG_NAME"

# 1. Release 编译
echo "🔨 Step 1/5: swift build -c release..."
cd "$PROJECT_DIR"
swift build -c release

# 2. 创建 .app bundle 结构
echo "📂 Step 2/5: 创建 .app bundle..."
rm -rf "$APP_BUNDLE"
mkdir -p "$APP_BUNDLE/Contents/MacOS"
mkdir -p "$APP_BUNDLE/Contents/Resources"

# 3. 复制可执行文件
echo "📋 Step 3/5: 复制可执行文件..."
cp "$BUILD_DIR/$APP_NAME" "$APP_BUNDLE/Contents/MacOS/"

# 4. 创建 Info.plist
echo "📝 Step 4/5: 创建 Info.plist..."
cat > "$APP_BUNDLE/Contents/Info.plist" << 'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleName</key>
    <string>FloatingMonitor</string>
    <key>CFBundleDisplayName</key>
    <string>Floating Monitor</string>
    <key>CFBundleIdentifier</key>
    <string>com.floatingmonitor.app</string>
    <key>CFBundleVersion</key>
    <string>1.0.0</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0.0</string>
    <key>CFBundleExecutable</key>
    <string>FloatingMonitor</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>LSMinimumSystemVersion</key>
    <string>14.0</string>
    <key>LSUIElement</key>
    <true/>
    <key>NSHighResolutionCapable</key>
    <true/>
</dict>
</plist>
PLIST

# 复制 Resources
if [ -d "$PROJECT_DIR/Sources/Resources" ]; then
    cp -R "$PROJECT_DIR/Sources/Resources/"* "$APP_BUNDLE/Contents/Resources/" 2>/dev/null || true
fi

# 5. 创建 DMG
echo "💿 Step 5/5: 创建 DMG..."
rm -rf "$STAGING"
mkdir -p "$STAGING"
cp -R "$APP_BUNDLE" "$STAGING/"

# 创建 Applications 快捷方式
ln -s /Applications "$STAGING/Applications"

rm -f "$DMG_NAME"
hdiutil create -volname "$APP_NAME" \
    -srcfolder "$STAGING" \
    -ov -format UDZO \
    "$DMG_NAME"

# 清理
rm -rf "$STAGING"

echo ""
echo "✅ DMG 创建成功: $DMG_NAME"
ls -lh "$DMG_NAME"
