# ========================
# Global build arguments
# ========================
ARG CONF_NUM

# ========================
# Dependencies stage
# ========================
FROM golang:alpine AS deps
ARG CONF_NUM

WORKDIR /app

COPY go.mod go.sum ./
RUN sed -i '/replace/d' go.mod
RUN go mod download

# ========================
# Builder stage
# ========================
FROM golang:alpine AS builder
ARG CONF_NUM

WORKDIR /oc-discovery

# Reuse Go cache
COPY --from=deps /go/pkg /go/pkg
COPY --from=deps /app/go.mod /app/go.sum ./

# App sources
COPY . .
# Clean replace directives again (safety)
RUN sed -i '/replace/d' go.mod

# Build package
RUN go install github.com/beego/bee/v2@latest
RUN bee pack

# Extract bundle
RUN mkdir -p /app/extracted \
 && tar -zxvf oc-discovery.tar.gz -C /app/extracted

# ========================
# Runtime stage
# ========================
FROM golang:alpine
ARG CONF_NUM

WORKDIR /app

RUN mkdir ./pem

COPY --from=builder /app/extracted/pem/private${CONF_NUM:-1}.pem ./pem/private.pem
COPY --from=builder /app/extracted/psk ./psk
COPY --from=builder /app/extracted/pem/public${CONF_NUM:-1}.pem ./pem/public.pem

COPY --from=builder /app/extracted/oc-discovery /usr/bin/oc-discovery
COPY --from=builder /app/extracted/docker_discovery${CONF_NUM:-1}.json /etc/oc/discovery.json

EXPOSE 400${CONF_NUM:-1}

ENTRYPOINT ["oc-discovery"]