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/proxy
ARG ARGUS_BUILD_UID=2133
ARG ARGUS_BUILD_GID=2015
ENV ARGUS_BUILD_UID=${ARGUS_BUILD_UID}
ENV ARGUS_BUILD_GID=${ARGUS_BUILD_GID}

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

# 创建 proxy 用户（可自定义 UID/GID）
# 创建 proxy 用户组
RUN set -eux; \
    if ! getent group "${ARGUS_BUILD_GID}" >/dev/null; then \
        groupadd -g "${ARGUS_BUILD_GID}" web_proxy || true; \
    fi; \
    if id web_proxy >/dev/null 2>&1; then \
        current_uid="$(id -u web_proxy)"; \
        if [ "$current_uid" != "${ARGUS_BUILD_UID}" ] && ! getent passwd "${ARGUS_BUILD_UID}" >/dev/null; then \
            usermod -u "${ARGUS_BUILD_UID}" web_proxy; \
        fi; \
        usermod -g "${ARGUS_BUILD_GID}" web_proxy || true; \
    else \
        if ! getent passwd "${ARGUS_BUILD_UID}" >/dev/null; then \
            useradd -M -s /usr/sbin/nologin -u "${ARGUS_BUILD_UID}" -g "${ARGUS_BUILD_GID}" web_proxy; \
        else \
            echo "UID ${ARGUS_BUILD_UID} already exists; skip creating user 'web_proxy'"; \
        fi; \
    fi; \
    chown -R "${ARGUS_BUILD_UID}:${ARGUS_BUILD_GID}" ${FRONTEND_BASE_PATH} /private/argus/etc /usr/local/bin || true

# 配置内网 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 配置（保证 React 前端路由兼容）
COPY src/web/build_tools/proxy/nginx.conf.template /etc/nginx/nginx.conf.template
COPY src/web/build_tools/proxy/conf.d/ /etc/nginx/conf.d/

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

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

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

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

# 暴露端口
EXPOSE 80

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

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