#!/bin/bash
# create_app_bundle.sh - 将 SPM 构建产物打包为 .app bundle
# Usage: ./scripts/create_app_bundle.sh [debug|release]

set -e

BUILD_MODE="${1:-debug}"
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BUILD_DIR="$PROJECT_DIR/.build"
BUNDLE_DIR="$BUILD_DIR/$BUILD_MODE/VoiceInput.app"
EXEC_SRC="$BUILD_DIR/$BUILD_MODE/VoiceInput"
CONTENTS_DIR="$BUNDLE_DIR/Contents"
MACOS_DIR="$CONTENTS_DIR/MacOS"
RESOURCES_DIR="$CONTENTS_DIR/Resources"

echo "📦 Creating app bundle at $BUNDLE_DIR..."

# 清空并创建目录结构
rm -rf "$BUNDLE_DIR"
mkdir -p "$MACOS_DIR"
mkdir -p "$RESOURCES_DIR"

# 复制可执行文件
cp "$EXEC_SRC" "$MACOS_DIR/VoiceInput"
chmod +x "$MACOS_DIR/VoiceInput"

# 复制 Info.plist 和图标
cp "$PROJECT_DIR/Sources/Resources/Info.plist" "$CONTENTS_DIR/Info.plist"
if [ -f "$PROJECT_DIR/Sources/Resources/AppIcon.icns" ]; then
    cp "$PROJECT_DIR/Sources/Resources/AppIcon.icns" "$RESOURCES_DIR/AppIcon.icns"
fi

# 更新 Info.plist 引用图标
/usr/libexec/PlistBuddy -c "Add :CFBundleIconFile string AppIcon" "$CONTENTS_DIR/Info.plist" 2>/dev/null || true

# 创建 PkgInfo
echo -n 'APPL????' > "$CONTENTS_DIR/PkgInfo"

echo "✅ App bundle created: $BUNDLE_DIR"
