# ============================================================
# NetBox 4.5 – Python 3.12 / Alpine
# Custom validators  → baked in via COPY
# Custom scripts     → mounted as volume at runtime
# Plugins & extra deps  → baked in via pip
# configuration.py     → mounted as volume at runtime
# ============================================================

# ── Stage 1: build wheel cache ────────────────────────────────
ARG PYTHON_VERSION

FROM python:${PYTHON_VERSION}-alpine AS builder

ARG NETBOX_VERSION
LABEL org.opencontainers.image.version=$NETBOX_VERSION

RUN apk update && apk add --no-cache \
  build-base \
  cargo \
  curl \
  git \
  libffi-dev \
  openssl-dev \
  postgresql-dev \
  xmlsec-dev \
  zlib-dev

WORKDIR /build

# Download NetBox source
RUN curl -fsSL \
    "https://github.com/netbox-community/netbox/archive/refs/tags/v${NETBOX_VERSION}.tar.gz" \
    | tar -xz --strip-components=1

# Install NetBox core requirements
RUN pip install --upgrade pip && \
  pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt

# ── Install plugins & extra deps here ────────────────────────
COPY local_requirements.txt /build/local_requirements.txt
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r /build/local_requirements.txt

# ── Stage 2: runtime image ────────────────────────────────────
FROM python:${PYTHON_VERSION}-alpine AS runtime

LABEL org.opencontainers.image.title="netbox" \
      org.opencontainers.image.version="${NETBOX_VERSION}" \
      org.opencontainers.image.description="NetBox network source of truth"

# Runtime OS deps only (no build tools)
RUN apk add --no-cache \
  bash \
  curl \
  libffi \
  libpq \
  libxslt \
  openssl \
  xmlsec \
  zlib && \
  addgroup -S netbox && \
  adduser  -S -G netbox -h /opt/netbox netbox

WORKDIR /opt/netbox

# Copy NetBox source from builder
COPY --from=builder /build .

# Install all pre-built wheels (core + plugins)
COPY --from=builder /wheels /wheels
RUN pip install --no-cache-dir --no-index --find-links=/wheels /wheels/*.whl && \
    rm -rf /wheels

# Create directories NetBox expects to own
RUN mkdir -p \
  netbox/media \
  netbox/reports \
  netbox/scripts \
  netbox/static && \
  chown -R netbox:netbox /opt/netbox

# ── Volume mount points ───────────────────────────────────────
#
#  /opt/netbox/netbox/netbox/configuration.py
#      → your configuration.py
#
#  /opt/netbox/netbox/media/
#      → uploaded media (persist across restarts)
#
VOLUME ["/opt/netbox/netbox/media"]
VOLUME ["/opt/netbox/netbox/static"]

# Entrypoint script handles: collectstatic, migrate, then gunicorn/worker
COPY --chown=netbox:netbox ./entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

USER netbox

ENTRYPOINT ["/entrypoint.sh"]
CMD ["gunicorn"]
