FROM python:3.11-slim

SHELL ["/bin/bash", "-c"]

ARG PIP_INDEX_URL=
ARG USE_OFFLINE=0
ARG USE_INTRANET=false

ENV PIP_NO_CACHE_DIR=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONPATH=/app

USER root

WORKDIR /app

COPY ./src/master/requirements.txt ./requirements.txt
COPY ./src/master/offline_wheels/ /opt/offline_wheels/

RUN set -euxo pipefail \
    && if [[ "$USE_OFFLINE" == "1" ]]; then \
         python -m pip install --no-index --find-links /opt/offline_wheels pip && \
         python -m pip install --no-index --find-links /opt/offline_wheels -r requirements.txt; \
       else \
         python -m pip install --upgrade pip && \
         if [[ -n "$PIP_INDEX_URL" ]]; then \
              PIP_INDEX_URL="$PIP_INDEX_URL" python -m pip install -r requirements.txt; \
         else \
              python -m pip install -r requirements.txt; \
         fi; \
       fi

# 配置内网 apt 源并安装常用工具
RUN if [[ "$USE_INTRANET" == "true" ]]; then \
        echo "Configuring intranet apt sources" && \
        if [[ -f /etc/apt/sources.list ]]; then cp /etc/apt/sources.list /etc/apt/sources.list.bak; fi && \
        mkdir -p /etc/apt && \
        echo "deb [trusted=yes] http://10.68.64.1/ubuntu2204/ jammy main" > /etc/apt/sources.list && \
        rm -rf /etc/apt/sources.list.d && \
        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-get update && \
    apt-get install -y supervisor net-tools inetutils-ping && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 运行期切换到运行所需的 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

RUN mkdir -p /var/log/supervisor

COPY ./src/master/build/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY ./src/master/build/start-master.sh /usr/local/bin/start-master.sh
COPY ./src/master/build/dns-monitor.sh /usr/local/bin/dns-monitor.sh
RUN chmod +x /usr/local/bin/start-master.sh /usr/local/bin/dns-monitor.sh

COPY ./src/master/app ./app

EXPOSE 3000

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
