# --- Stage 1: Build ---
FROM --platform=$BUILDPLATFORM golang:1.24-bullseye AS builder

ARG BUILDPLATFORM
ARG TARGETPLATFORM
ARG TARGETARCH

# Enable CGO for the libc-dev dependencies required by CoreDNS
ENV CGO_ENABLED=1

RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    make \
    gcc \
    libc6-dev \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Set up source directory
WORKDIR /src

# 1. Clone CoreDNS v1.13.1
RUN git clone -b v1.13.1 --depth 1 https://github.com/coredns/coredns.git .

# 2. Inject your custom plugin.cfg
COPY plugin.cfg /src/plugin.cfg

## 3. Fetch external plugins and tidy modules
## We use a cache mount for /go/pkg/mod to make subsequent builds much faster
#RUN --mount=type=cache,target=/go/pkg/mod \
#    go get github.com/zhoreeq/coredns-meshname \
#    github.com/zhoreeq/coredns-meship && \
#    go mod tidy
#
## 4. Compile CoreDNS
# 3. Register plugins and fetch dependencies
# 'go generate' creates the necessary glue code for the new plugins
RUN go generate && \
    go mod tidy && \
    go get github.com/zhoreeq/coredns-meshname && \
    go get github.com/zhoreeq/coredns-meship && \
    go mod tidy

# 4. Compile with optimized flags
RUN make

# --- Stage 2: Runtime ---
FROM debian:stable-slim

ARG TARGETARCH

# Install runtime dependencies:
# - ca-certificates: for secure upstream forwarding (TLS)
# - dnsutils: provides 'nslookup' for the Docker healthcheck
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    dnsutils \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copy the compiled binary and the Corefile
COPY --from=builder /src/coredns /coredns
COPY ./Corefile /Corefile

# copy entrypoint script that updates alt hints
COPY ./entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

# Expose standard DNS ports
EXPOSE 53/tcp 53/udp 853/tcp 443/tcp

# Run our wrapper entrypoint which updates hints then launches CoreDNS
ENTRYPOINT ["/entrypoint.sh"]
CMD ["-conf", "/Corefile"]
