#!/bin/bash
set -e

echo "=== UnityFramework 升级脚本 ==="
echo ""

# 检查参数
if [ "$#" -ne 1 ]; then
    echo "用法: $0 <新的真机Framework路径>"
    echo "示例: $0 /path/to/new/UnityFramework.framework"
    exit 1
fi

NEW_FRAMEWORK="$1"
REPO_DIR="/Users/ezio/Documents/work/project/flutter_unity_pod"
STUB_DIR="$REPO_DIR/simulator_stub"
BUILD_DIR="$REPO_DIR/build"

# 验证新的 framework 是否存在
if [ ! -d "$NEW_FRAMEWORK" ]; then
    echo "❌ 错误: Framework 不存在: $NEW_FRAMEWORK"
    exit 1
fi

# 验证是否是真机架构
ARCH=$(lipo -info "$NEW_FRAMEWORK/UnityFramework" 2>/dev/null | grep "arm64" || echo "")
if [ -z "$ARCH" ]; then
    echo "❌ 错误: Framework 不包含 arm64 架构，请确保是真机版本"
    exit 1
fi

echo "✅ 验证通过: 找到真机 Framework"
echo ""

# 清理之前的构建
echo "1. 清理旧构建..."
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"

# 备份当前 XCFramework（可选）
if [ -d "$REPO_DIR/UnityLibrary/UnityFramework.xcframework" ]; then
    BACKUP_DIR="$REPO_DIR/backup_$(date +%Y%m%d_%H%M%S)"
    echo "2. 备份当前 XCFramework 到: $BACKUP_DIR"
    mkdir -p "$BACKUP_DIR"
    cp -r "$REPO_DIR/UnityLibrary/UnityFramework.xcframework" "$BACKUP_DIR/"
fi

echo "3. 编译模拟器空壳 framework..."
cd "$STUB_DIR"

# 编译 arm64 模拟器版本
xcrun clang -arch arm64 \
    -isysroot $(xcrun --sdk iphonesimulator --show-sdk-path) \
    -target arm64-apple-ios13.0-simulator \
    -dynamiclib \
    -o "$BUILD_DIR/UnityFramework_sim_arm64" \
    -framework Foundation -framework UIKit \
    -install_name @rpath/UnityFramework.framework/UnityFramework \
    UnityFrameworkStub.m

# 编译 x86_64 模拟器版本
xcrun clang -arch x86_64 \
    -isysroot $(xcrun --sdk iphonesimulator --show-sdk-path) \
    -target x86_64-apple-ios13.0-simulator \
    -dynamiclib \
    -o "$BUILD_DIR/UnityFramework_sim_x86_64" \
    -framework Foundation -framework UIKit \
    -install_name @rpath/UnityFramework.framework/UnityFramework \
    UnityFrameworkStub.m

echo "4. 合并模拟器架构..."
lipo -create \
    "$BUILD_DIR/UnityFramework_sim_arm64" \
    "$BUILD_DIR/UnityFramework_sim_x86_64" \
    -output "$BUILD_DIR/UnityFramework_sim"

echo "5. 创建模拟器 framework 结构..."
SIM_FRAMEWORK="$BUILD_DIR/UnityFramework-sim.framework"
mkdir -p "$SIM_FRAMEWORK/Headers"
mkdir -p "$SIM_FRAMEWORK/Modules"

# 复制二进制
cp "$BUILD_DIR/UnityFramework_sim" "$SIM_FRAMEWORK/UnityFramework"

# 从新的真机 framework 复制头文件
cp -r "$NEW_FRAMEWORK/Headers/" "$SIM_FRAMEWORK/Headers/"

# 创建 module.modulemap
cat > "$SIM_FRAMEWORK/Modules/module.modulemap" << 'EOF'
framework module UnityFramework {
  umbrella header "UnityFramework.h"
  export *
  module * { export * }
}
EOF

# 创建 Info.plist
cat > "$SIM_FRAMEWORK/Info.plist" << 'EOF'
<?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>CFBundleExecutable</key>
    <string>UnityFramework</string>
    <key>CFBundleIdentifier</key>
    <string>com.unity3d.framework</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>UnityFramework</string>
    <key>CFBundlePackageType</key>
    <string>FMWK</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>MinimumOSVersion</key>
    <string>13.0</string>
</dict>
</plist>
EOF

echo "6. 创建 XCFramework..."
# 创建临时目录
DEVICE_BUILD="$BUILD_DIR/device"
SIM_BUILD="$BUILD_DIR/simulator"
mkdir -p "$DEVICE_BUILD" "$SIM_BUILD"

# 复制新的真机 framework
cp -r "$NEW_FRAMEWORK" "$DEVICE_BUILD/UnityFramework.framework"

echo "6.5. 优化 framework 大小（strip 符号表）..."
# 移除本地符号和调试信息，保留外部符号（减少约100MB）
strip -x "$DEVICE_BUILD/UnityFramework.framework/UnityFramework"
echo "   优化后大小: $(du -sh "$DEVICE_BUILD/UnityFramework.framework/UnityFramework" | awk '{print $1}')"

# 移动模拟器 framework
mv "$SIM_FRAMEWORK" "$SIM_BUILD/UnityFramework.framework"

# 创建 XCFramework
xcodebuild -create-xcframework \
    -framework "$DEVICE_BUILD/UnityFramework.framework" \
    -framework "$SIM_BUILD/UnityFramework.framework" \
    -output "$BUILD_DIR/UnityFramework.xcframework"

echo "7. 替换旧的 XCFramework..."
rm -rf "$REPO_DIR/UnityLibrary/UnityFramework.xcframework"
cp -r "$BUILD_DIR/UnityFramework.xcframework" "$REPO_DIR/UnityLibrary/"

echo ""
echo "✅ 升级完成！新的 XCFramework 已创建在:"
echo "   $REPO_DIR/UnityLibrary/UnityFramework.xcframework"
echo ""
echo "📝 后续步骤:"
echo "   1. 检查 XCFramework 是否正常"
echo "   2. 更新 podspec 版本号（如果需要）"
echo "   3. 提交到 git: git add -A && git commit -m 'Update Unity framework'"
echo "   4. 打标签: git tag 1.0.x"
echo "   5. 推送: git push origin main && git push origin 1.0.x"
echo ""
