# 第一阶段：构建环境
FROM node:16.20.2-bullseye-slim AS builder

# 安装基础依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    libgtk-3-0 \
    libnotify4 \
    libnss3 \
    libxss1 \
    libxtst6 \
    xdg-utils \
    libatspi2.0-0 \
    libuuid1 \
    libsecret-1-0 \
    curl \
    tar \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制项目文件
COPY . .

# 安装 HBuilderX CLI
RUN npm run hb-setup
ENV PATH="/opt/HBuilderX:${PATH}"

# 设置构建参数
ARG BUILD_PLATFORM=h5
ENV UNI_PLATFORM=$BUILD_PLATFORM

# 执行构建
RUN hbuilderx build --project /app --platform $BUILD_PLATFORM

# ===================================================
# 第二阶段：运行环境（按平台分发）
# ===================================================

# H5 运行环境
FROM nginx:1.25.2-alpine AS h5-runtime
COPY --from=builder /app/unpackage/dist/build/h5 /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

## Android 运行环境（仅用于保存 APK）
#FROM alpine:3.18 AS android-runtime
#COPY --from=builder /app/unpackage/dist/build/android /app
#VOLUME /output
#CMD ["sh", "-c", "cp /app/*.apk /output"]
#
## iOS 运行环境（仅用于保存 IPA）
#FROM alpine:3.18 AS ios-runtime
#COPY --from=builder /app/unpackage/dist/build/ios /app
#VOLUME /output
#CMD ["sh", "-c", "cp /app/*.ipa /output"]

# ===================================================
# 最终阶段：根据构建参数选择目标平台
# ===================================================
ARG TARGET_PLATFORM=h5
FROM ${TARGET_PLATFORM}-runtime AS final
