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

# 设置时区
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# 使用国内镜像源替换默认源
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list

# 安装基础依赖
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    curl \
    tar \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制项目文件
COPY . .

# 关键修改：直接复制已解压的 HBuilderX 目录
COPY ./HBuilderX /opt/HBuilderX

# 检查并设置权限
RUN chmod +x /opt/HBuilderX/cli && \
    if [ ! -f "/opt/HBuilderX/cli" ]; then \
        echo "HBuilderX CLI 安装失败！"; \
        exit 1; \
    else \
        echo "HBuilderX CLI 安装成功"; \
        /opt/HBuilderX/cli --version; \
    fi

# 设置环境变量
ENV PATH="/opt/HBuilderX:${PATH}"

# 安装项目依赖 - 使用国内npm源
RUN npm config set registry https://registry.npmmirror.com && \
    npm install

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

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

# ===================================================
# 第二阶段：运行环境
# ===================================================

# H5 运行环境
FROM nginx:1.25.2-alpine AS h5-runtime

# 复制自定义Nginx配置
COPY --from=builder /app/nginx.conf /etc/nginx/conf.d/default.conf

# 复制构建产物
COPY --from=builder /app/unpackage/dist/build/h5 /usr/share/nginx/html

# 暴露端口
EXPOSE 8333

# 启动命令
CMD ["nginx", "-g", "daemon off;"]
