# ==================== 第一阶段：构建前端 ====================
FROM docker.m.daocloud.io/node:18-alpine AS builder
WORKDIR /app
# 配置Alpine国内镜像源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

COPY package*.json ./

RUN npm install --registry=https://registry.npmmirror.com

COPY . .

RUN npm run build

# ==================== 第二阶段：部署到Nginx ====================
FROM docker.m.daocloud.io/nginx:alpine

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

# 复制nginx配置文件
COPY ngnix.conf /etc/nginx/conf.d/default.conf

# 复制SSL证书
COPY ssl/* /etc/nginx/ssl/

# 启动时自动获取宿主机内网 IP，替换 __API_HOST__ 占位符
RUN printf '%s\n' \
    '#!/bin/sh' \
    'set -e' \
    'if [ -n "$API_HOST" ]; then' \
    '    HOST_IP="$API_HOST"' \
    'else' \
    '    HOST_IP=$(route -n 2>/dev/null | grep "^0.0.0.0" | tr -s " " | cut -d " " -f2)' \
    'fi' \
    'sed -i "s/__API_HOST__/$HOST_IP/g" /etc/nginx/conf.d/default.conf' \
    > /docker-entrypoint.d/01-set-api-host.sh && chmod +x /docker-entrypoint.d/01-set-api-host.sh

EXPOSE 80 443

CMD ["nginx", "-g", "daemon off;"]
