#!/bin/bash

# 简化的 macOS DMG 构建脚本（无签名版本）
# 注意：此版本需要用户在安装时手动允许

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 开始构建 macOS DMG（简化版本）...${NC}"

# 清理之前的构建
echo -e "${YELLOW}🧹 清理之前的构建...${NC}"
flutter clean

# 构建 Flutter macOS 应用
echo -e "${YELLOW}🔨 构建 Flutter macOS 应用...${NC}"
flutter build macos --release

# 检查应用是否构建成功
APP_PATH="build/macos/Build/Products/Release/BearVPN.app"
if [ ! -d "$APP_PATH" ]; then
    echo -e "${RED}❌ 应用构建失败: $APP_PATH 不存在${NC}"
    exit 1
fi

echo -e "${GREEN}✅ 应用构建成功: $APP_PATH${NC}"

# 创建 DMG
echo -e "${YELLOW}📦 创建 DMG 安装包...${NC}"

DMG_PATH="build/macos/Build/Products/Release/BearVPN.dmg"
TEMP_DMG="build/macos/Build/Products/Release/temp.dmg"

# 创建临时 DMG
hdiutil create -srcfolder "$APP_PATH" -volname "Kaer VPN" -fs HFS+ -fsargs "-c c=64,a=16,e=16" -format UDRW -size 200m "$TEMP_DMG"

# 挂载临时 DMG
echo -e "${YELLOW}📂 挂载临时 DMG...${NC}"
MOUNT_OUTPUT=$(hdiutil attach -readwrite -noverify -noautoopen "$TEMP_DMG")
MOUNT_POINT=$(echo "$MOUNT_OUTPUT" | grep "/Volumes" | awk '{print $3}')

if [ -z "$MOUNT_POINT" ]; then
    echo -e "${RED}❌ 无法挂载 DMG${NC}"
    exit 1
fi

echo -e "${GREEN}✅ DMG 已挂载到: $MOUNT_POINT${NC}"

# 等待挂载完成
sleep 3

# 设置 DMG 属性
echo -e "${YELLOW}🎨 设置 DMG 属性...${NC}"

# 创建应用程序链接
ln -s /Applications "$MOUNT_POINT/Applications"

# 设置窗口属性
echo -e "${YELLOW}🖼️ 设置窗口属性...${NC}"
osascript <<EOF
tell application "Finder"
    tell disk "Kaer VPN"
        open
        set current view of container window to icon view
        set toolbar visible of container window to false
        set statusbar visible of container window to false
        set the bounds of container window to {400, 100, 900, 450}
        set theViewOptions to the icon view options of container window
        set arrangement of theViewOptions to not arranged
        set icon size of theViewOptions to 128
        make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
        set position of item "BearVPN.app" of container window to {150, 200}
        set position of item "Applications" of container window to {350, 200}
        close
        open
        update without registering applications
        delay 2
    end tell
end tell
EOF

# 卸载 DMG
echo -e "${YELLOW}📤 卸载 DMG...${NC}"
hdiutil detach "$MOUNT_POINT" -force

# 转换为只读 DMG
hdiutil convert "$TEMP_DMG" -format UDZO -imagekey zlib-level=9 -o "$DMG_PATH"

# 清理临时文件
rm "$TEMP_DMG"

echo -e "${GREEN}✅ DMG 创建成功: $DMG_PATH${NC}"

# 显示 DMG 信息
echo -e "${YELLOW}📊 DMG 信息:${NC}"
hdiutil imageinfo "$DMG_PATH"

echo -e "${GREEN}🎉 DMG 构建完成！${NC}"
echo -e "${GREEN}📁 文件位置: $DMG_PATH${NC}"
echo -e "${GREEN}📏 文件大小: $(du -h "$DMG_PATH" | cut -f1)${NC}"

echo -e "${YELLOW}⚠️  注意：此 DMG 未签名，用户安装时需要在安全隐私设置中手动允许${NC}"
echo -e "${YELLOW}💡 要避免手动允许，请使用 build_macos_dmg.sh 脚本进行签名和公证${NC}"
