#!/bin/bash
# 把裸可执行文件打成 macOS .app 应用包（在 Mac 上运行）
set -e

SRC="$HOME/Applications/2fa-desktop-password"
APP="$HOME/Applications/2FA Desktop 密码版.app"
WORK="$HOME/Downloads/2fa-mac-install"

if [ ! -d "$SRC" ]; then
  echo "❌ 找不到 $SRC —— 请先跑 install-2fa-mac.sh"
  exit 1
fi

echo "=== 打包 2FA Desktop 为 .app ==="

# 1. 建目录结构
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS"
mkdir -p "$APP/Contents/Resources"

# 2. 拷贝全部文件到 Resources（程序从 MacOS/ 启动，用相对路径找依赖）
cp -R "$SRC"/* "$APP/Contents/MacOS/"

# 3. 图标
if [ -f "$WORK/AppIcon.icns" ]; then
  cp "$WORK/AppIcon.icns" "$APP/Contents/Resources/AppIcon.icns"
  echo "  图标已加入"
else
  echo "  ⚠️  没找到 AppIcon.icns，跳过图标"
fi

# 4. Info.plist
cat > "$APP/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>2FA Desktop</string>
    <key>CFBundleDisplayName</key>
    <string>2FA Desktop 密码版</string>
    <key>CFBundleIdentifier</key>
    <string>com.whitepaseo.2fadesktop</string>
    <key>CFBundleVersion</key>
    <string>1.0.0</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0.0</string>
    <key>CFBundleExecutable</key>
    <string>TwoFactorAuthDesktop</string>
    <key>CFBundleIconFile</key>
    <string>AppIcon</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>LSMinimumSystemVersion</key>
    <string>11.0</string>
    <key>NSHighResolutionCapable</key>
    <true/>
    <key>LSApplicationCategoryType</key>
    <string>public.app-category.utilities</string>
</dict>
</plist>
PLIST

# 5. 去隔离 + 签名
xattr -dr com.apple.quarantine "$APP" 2>/dev/null || true
codesign --force --deep --sign - "$APP" 2>&1 | grep -v "replacing existing signature" || true

echo
echo "=== 完成 ==="
echo "应用位置: $APP"
echo
echo "现在可以："
echo "  1. 双击打开（不会再开终端）"
echo "  2. 拖到 Dock 或 Applications 文件夹"
echo "  3. 在 Launchpad 里搜「2FA Desktop」"
