#!/usr/bin/env bash
# 将运行时包同步到 scratch-gui/static/unity/
# 与 OSS unitycdndir 内容完全一致：Build/ + StreamingAssets/ + levels-database.*
#
#   bash tools/sync-unity-package-to-static.sh <packDir> <staticUnityDir>
set -euo pipefail

PACK_DIR="$(cd "${1:?packDir}" && pwd)"
UNITY_STATIC="$(cd "${2:?staticUnityDir}" && pwd)"
DRY_RUN="${DRY_RUN:-0}"

if [[ ! -f "$PACK_DIR/Build/mstest5.loader.js" ]]; then
  echo "错误: 缺少 $PACK_DIR/Build/mstest5.loader.js" >&2
  exit 1
fi
if [[ ! -f "$PACK_DIR/StreamingAssets/aa/catalog.json" ]]; then
  echo "错误: 缺少 $PACK_DIR/StreamingAssets/aa/catalog.json" >&2
  exit 1
fi

mkdir -p "$UNITY_STATIC/Build" "$UNITY_STATIC/StreamingAssets"

RSYNC_FLAGS=(-a --delete)
[[ "$DRY_RUN" -eq 1 ]] && RSYNC_FLAGS=(-a -n -v)

echo "==> 同步运行时包 → static/unity（与 OSS unitycdndir 相同）"
echo "    源: $PACK_DIR"
echo "    目标: $UNITY_STATIC"

rsync "${RSYNC_FLAGS[@]}" "$PACK_DIR/Build/" "$UNITY_STATIC/Build/"
rsync "${RSYNC_FLAGS[@]}" "$PACK_DIR/StreamingAssets/" "$UNITY_STATIC/StreamingAssets/"

for db in levels-database.json levels-database.json.br; do
  if [[ -f "$PACK_DIR/$db" ]]; then
    if [[ "$DRY_RUN" -eq 1 ]]; then
      echo "    [dry-run] cp $PACK_DIR/$db → $UNITY_STATIC/"
    else
      cp "$PACK_DIR/$db" "$UNITY_STATIC/$db"
      echo "    copied $db"
    fi
  fi
done

if [[ "$DRY_RUN" -eq 0 ]]; then
  for legacy in index.js application.js cocos-bridge.js assets cocos-js src index.html TemplateData; do
    if [[ -e "$UNITY_STATIC/$legacy" ]]; then
      rm -rf "$UNITY_STATIC/$legacy"
      echo "    removed legacy: $legacy"
    fi
  done
fi

echo "==> 完成。usecdn:false → /unity/ ；usecdn:true → unitycdndir（文件相同）"
