FROM grafana/grafana:11.1.0

USER root

# 构建参数：是否使用内网镜像
ARG USE_INTRANET=false

# 根据是否为内网构建切换 apk 源
RUN if [ "$USE_INTRANET" = "true" ]; then \
        echo "Configuring intranet apk repositories..." && \
        sed -i 's#https\?://[^/]\+#http://10.68.64.1#g' /etc/apk/repositories; \
    else \
        echo "Configuring public apk repositories..." && \
        sed -i 's#https\?://[^/]\+#https://mirrors.aliyun.com#g' /etc/apk/repositories; \
    fi

# 安装必要的工具
RUN apk add --no-cache \
        supervisor \
        net-tools \
        iputils \
        vim \
        bash

# 部署镜像时恢复到部署侧使用的内网镜像源
RUN if [ "$USE_INTRANET" = "true" ]; then \
        sed -i 's#https\?://[^/]\+#https://10.92.132.52/mirrors#g' /etc/apk/repositories; \
    fi

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

# 设置 Grafana 基础路径环境变量
ENV GRAFANA_BASE_PATH=/private/argus/metric/grafana

# 设置用户和组ID环境变量
ARG ARGUS_BUILD_UID=2133
ARG ARGUS_BUILD_GID=2015

ENV ARGUS_BUILD_UID=${ARGUS_BUILD_UID} \
    ARGUS_BUILD_GID=${ARGUS_BUILD_GID}

# 创建基本目录结构
RUN mkdir -p /private/argus/etc \
    && mkdir -p ${GRAFANA_BASE_PATH}/data \
    && mkdir -p ${GRAFANA_BASE_PATH}/logs \
    && mkdir -p ${GRAFANA_BASE_PATH}/plugins \
    && mkdir -p ${GRAFANA_BASE_PATH}/provisioning/datasources \
    && mkdir -p ${GRAFANA_BASE_PATH}/provisioning/dashboards \
    && mkdir -p ${GRAFANA_BASE_PATH}/data/sessions \
    && mkdir -p ${GRAFANA_BASE_PATH}/data/dashboards \
    && mkdir -p ${GRAFANA_BASE_PATH}/config \
    && mkdir -p /etc/grafana \
    && mkdir -p /var/lib/grafana \
    && mkdir -p /var/log/grafana

# 修改 Grafana 用户 UID/GID 并授权
RUN deluser grafana && \
    addgroup -g ${ARGUS_BUILD_GID} grafana && \
    adduser -u ${ARGUS_BUILD_UID} -G grafana -s /bin/sh -D grafana && \
    chown -R grafana:grafana /var/lib/grafana /etc/grafana /var/log/grafana ${GRAFANA_BASE_PATH}

# 复制配置文件到容器内临时位置
COPY grafana.ini /tmp/grafana.ini
COPY datasources/datasources.yml /tmp/datasources.yml
COPY dashboards/dashboards.yml /tmp/dashboards.yml
COPY dashboards/default_dashboard_by_hostname.json /tmp/default_dashboard.json
COPY dashboards/default_cluster_dashboard.json /tmp/default_cluster_dashboard.json
COPY dashboards/default_dashboard_by_instance.json /tmp/default_dashboard_by_instance.json

# supervisor 配置
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# 启动脚本
COPY start-grafana-supervised.sh /usr/local/bin/start-grafana-supervised.sh
RUN chmod +x /usr/local/bin/start-grafana-supervised.sh

# 确保配置文件权限正确
RUN chown -R grafana:grafana /etc/grafana

COPY dns-monitor.sh /usr/local/bin/dns-monitor.sh
RUN chmod +x /usr/local/bin/dns-monitor.sh

USER root

EXPOSE 3000

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