# ========== 构建阶段 ==========
FROM node:20 AS builder

# 设置工作目录
WORKDIR /app/src/web

# 复制依赖文件并安装
COPY src/web/package*.json ./

RUN npm install

# 复制源码并打包
COPY src/web ./
RUN npm run build

# ========== 运行阶段 ==========
FROM ubuntu:24.04

USER root

# 安装 nginx 和 supervisor
RUN apt-get update && \
    apt-get install -y nginx supervisor curl vim net-tools inetutils-ping ca-certificates passwd && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

ENV FRONTEND_BASE_PATH=/private/argus/web/frontend
ENV ARGUS_UID=2133
ENV ARGUS_GID=2015

RUN mkdir -p ${FRONTEND_BASE_PATH} && \
    mkdir -p /private/argus/etc

# 创建 web 用户（可自定义 UID/GID）
# 创建 web 用户组
RUN groupadd -g ${ARGUS_GID} web

# 创建 web 用户并指定组
RUN useradd -M -s /usr/sbin/nologin -u ${ARGUS_UID} -g ${ARGUS_GID} web

RUN chown -R web:web ${FRONTEND_BASE_PATH} && \
    chown -R web:web /private/argus/etc && \
    chown -R web:web /usr/local/bin

# 配置内网 apt 源 (如果指定了内网选项)
RUN if [ "$USE_INTRANET" = "true" ]; then \
        echo "Configuring intranet apt sources..." && \
        cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
        echo "deb [trusted=yes] http://10.68.64.1/ubuntu2204/ jammy main" > /etc/apt/sources.list && \
        echo 'Acquire::https::Verify-Peer "false";' > /etc/apt/apt.conf.d/99disable-ssl-check && \
        echo 'Acquire::https::Verify-Host "false";' >> /etc/apt/apt.conf.d/99disable-ssl-check; \
    fi


# 配置部署时使用的 apt 源
RUN if [ "$USE_INTRANET" = "true" ]; then \
    echo "deb [trusted=yes] https://10.92.132.52/mirrors/ubuntu2204/ jammy main" > /etc/apt/sources.list; \
    fi

# 前端编译产物放到 nginx 目录
COPY --from=builder /app/src/web/dist /usr/share/nginx/html

# 复制 nginx 配置（保证 React 前端路由兼容）
COPY src/web/build_tools/frontend/nginx.conf /etc/nginx/nginx.conf
# COPY src/web/build_tools/frontend/conf.d/ /etc/nginx/conf.d/

# 复制 supervisor 配置
COPY src/web/build_tools/frontend/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# 创建 supervisor 日志目录
RUN mkdir -p /var/log/supervisor

# 复制启动脚本
COPY src/web/build_tools/frontend/start-web-supervised.sh /usr/local/bin/start-web-supervised.sh
RUN chmod +x /usr/local/bin/start-web-supervised.sh

# 复制 DNS 监控脚本
COPY src/web/build_tools/frontend/dns-monitor.sh /usr/local/bin/dns-monitor.sh
RUN chmod +x /usr/local/bin/dns-monitor.sh

# 复制健康检查脚本
COPY src/web/build_tools/frontend/health-check.sh /usr/local/bin/health-check.sh
RUN chmod +x /usr/local/bin/health-check.sh

# 暴露端口
EXPOSE 80

# 保持 root 用户，由 supervisor 控制 user 切换
USER root

# 以 supervisor 为入口
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
