#!/usr/bin/env bash
# 生成 OSS 上传清单（运行时包 build/mstest5 与本地 static/unity 相同，不再复制 cdn-upload）
#
#   bash tools/package-cdn-upload.sh
#   bash tools/package-cdn-upload.sh --cdn-base https://oss.example.com/game
#   bash tools/package-cdn-upload.sh --zip
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
BUILD_DIR="$PROJECT_DIR/build/web-desktop"
PACK_DIR="$PROJECT_DIR/build/mstest5"
DEPLOY_DIR="$PROJECT_DIR/build/deploy"
UNITY_REF="${UNITY_REF:-$HOME/tfrh/竞赛/mstest5}"
CDN_BASE=""
MAKE_ZIP=0
SKIP_BUILD=0
SKIP_PACK=0

usage() {
  cat <<'EOF'
用法: package-cdn-upload.sh [options]

  1. package-for-cdn → build/mstest5/（运行时包）
  2. write-deploy-manifest → build/deploy/（清单，不复制包）

运行时包 = 本地 static/unity = OSS unitycdndir（仅 URL 不同）

选项:
  --build DIR       Cocos 构建目录
  --pack DIR        运行时包目录（默认 build/mstest5）
  --cdn-base URL    OSS 根地址
  --zip             生成 build/mstest5-runtime.zip
  --skip-build      跳过构建检查
  --skip-pack       跳过打包，仅生成清单
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --build) BUILD_DIR="$2"; shift 2 ;;
    --pack) PACK_DIR="$2"; shift 2 ;;
    --cdn-base) CDN_BASE="$2"; shift 2 ;;
    --zip) MAKE_ZIP=1; shift ;;
    --skip-build) SKIP_BUILD=1; shift ;;
    --skip-pack) SKIP_PACK=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "未知参数: $1" >&2; usage; exit 1 ;;
  esac
done

if [[ "$SKIP_BUILD" -eq 0 ]]; then
  bash "$SCRIPT_DIR/verify-split-build.sh" "$BUILD_DIR"
fi

if [[ "$SKIP_PACK" -eq 0 ]]; then
  bash "$SCRIPT_DIR/package-for-project.sh" --build "$BUILD_DIR" --out "$PACK_DIR" \
    ${CDN_BASE:+--cdn-base "$CDN_BASE"} \
    ${MAKE_ZIP:+--zip}
else
  MANIFEST_ARGS=("$PACK_DIR" --manifest-dir "$DEPLOY_DIR")
  [[ -n "$CDN_BASE" ]] && MANIFEST_ARGS+=(--cdn-base "$CDN_BASE")
  [[ "$MAKE_ZIP" -eq 1 ]] && MANIFEST_ARGS+=(--zip)
  node "$SCRIPT_DIR/write-deploy-manifest.js" "${MANIFEST_ARGS[@]}"
fi

echo ""
echo "完成。"
echo "  运行时包（本地=CDN）: $PACK_DIR"
echo "  上传清单:             $DEPLOY_DIR/UPLOAD-MANIFEST.txt"
