#!/bin/bash
# Cocos → Unity mstest5 完全一致目录结构（参考 /Users/liuyufei/tfrh/竞赛/mstest5）
#
#   bash tools/package-for-cdn.sh
#   bash tools/package-for-cdn.sh --build build/web-desktop-001 --out "/Users/liuyufei/tfrh/竞赛/mstest5-cocos"

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
BUILD_DIR="$PROJECT_DIR/build/web-desktop"
OUT_DIR="$PROJECT_DIR/build/mstest5"
UNITY_REF="/Users/liuyufei/tfrh/竞赛/mstest5"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --build) BUILD_DIR="$2"; shift 2 ;;
    --out) OUT_DIR="$2"; shift 2 ;;
    --unity-ref) UNITY_REF="$2"; shift 2 ;;
    --to-unity-dir) OUT_DIR="/Users/liuyufei/tfrh/竞赛/mstest5-cocos"; shift ;;
    -h|--help)
      cat <<'EOF'
Usage: package-for-cdn.sh [--build DIR] [--out DIR] [--unity-ref DIR]

默认:
  --build  build/web-desktop
  --out    build/mstest5
  --unity-ref  /Users/liuyufei/tfrh/竞赛/mstest5

产物与 Unity 参考完全一致:
  index.html
  Build/mstest5.{loader.js,data.br,framework.js.br,wasm.br}
  StreamingAssets/aa/{catalog.json,settings.json,AddressablesLink/link.xml,WebGL/*.bundle}
  TemplateData/*
EOF
      exit 0
      ;;
    *) echo "Unknown: $1"; exit 1 ;;
  esac
done

BUILD_DIR="$(cd "$BUILD_DIR" 2>/dev/null && pwd || true)"
if [[ -z "$BUILD_DIR" || ! -f "$BUILD_DIR/index.html" ]]; then
  echo "Error: 请先 Cocos 构建 Web Desktop，目录: $BUILD_DIR"
  exit 1
fi
if [[ ! -f "$UNITY_REF/index.html" ]]; then
  echo "Error: Unity 参考包不存在: $UNITY_REF"
  exit 1
fi

node "$SCRIPT_DIR/package-for-cdn.js" "$BUILD_DIR" "$OUT_DIR" "$UNITY_REF"

echo ""
echo "对比 Unity 参考:"
echo "  diff -qr \"$UNITY_REF\" \"$OUT_DIR\" | head -30"
