# 第一阶段：构建环境
FROM node:20-alpine AS builder

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

# 使用阿里云镜像源
RUN echo "https://mirrors.aliyun.com/alpine/v3.19/main" > /etc/apk/repositories && \
    echo "https://mirrors.aliyun.com/alpine/v3.19/community" >> /etc/apk/repositories

# 安装基本依赖（最小化安装）
RUN apk add --no-cache \
    bash \
    qt5-qtbase \
    qt5-qtsvg \
    libx11 \
    libxext \
    icu

# 设置工作目录
WORKDIR /app

# 复制项目文件（最小化）
COPY package.json package-lock.json ./
COPY src ./src
COPY public ./public

# 复制 HBuilderX（从构建上下文）
COPY ./hbuilder_temp/opt/HBuilderX /opt/HBuilderX

# 修复权限
RUN chmod 755 /opt/HBuilderX/cli && \
    chmod 755 /opt/HBuilderX/HBuilderX && \
    find /opt/HBuilderX -name "lib*.so*" -exec chmod 755 {} \;

# 设置 Qt 库路径
ENV LD_LIBRARY_PATH=/opt/HBuilderX:$LD_LIBRARY_PATH

# 配置 npm 镜像源
RUN npm config set registry https://registry.npmmirror.com

# 安装项目依赖
RUN npm install --no-audit

# 登录和构建项目
ARG HB_USERNAME
ARG HB_PASSWORD
RUN /opt/HBuilderX/cli user login --username "$HB_USERNAME" --password "$HB_PASSWORD" && \
    /opt/HBuilderX/cli publish --platform h5 --project . --output dist

# 第二阶段：运行环境
FROM nginx:1.25-alpine

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

# 复制自定义 Nginx 配置
COPY nginx.conf /etc/nginx/conf.d/app.conf

# 从构建阶段复制构建产物
COPY --from=builder /app/dist /usr/share/nginx/html

# 暴露端口
EXPOSE 8333

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