# syntax=docker/dockerfile:1

ARG MODULE="inference"
ARG SERVICE="safety"

ARG APP_USER="${MODULE}-${SERVICE}"
ARG APP_RELATIVE_PATH="${MODULE}/${SERVICE}"

FROM python:3.10-slim as build
ARG APP_RELATIVE_PATH

WORKDIR /build

RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    && rm -rf /var/lib/apt/lists/*

COPY ./${APP_RELATIVE_PATH}/requirements.txt requirements.txt

RUN --mount=type=cache,target=/var/cache/pip \
    pip install                  \
      --cache-dir=/var/cache/pip \
      --target=lib               \
      -r requirements.txt

FROM python:3.10-slim as prod
ARG APP_USER
ARG APP_RELATIVE_PATH
ARG MODULE
ARG SERVICE

ENV APP_BASE="/opt/${MODULE}"
ENV APP_ROOT="${APP_BASE}/${SERVICE}"
ENV APP_LIBS="/var/opt/${APP_RELATIVE_PATH}/lib"
ENV SHARED_LIBS_BASE="${APP_BASE}/lib"

ENV PATH="${PATH}:${APP_LIBS}/bin"
ENV PYTHONPATH="${PYTHONPATH}:${APP_LIBS}"
ENV PORT="8002"

RUN adduser               \
      --disabled-password \
      "${APP_USER}" && \
    mkdir -p ${APP_ROOT} ${APP_LIBS} && \
    chown -R "${APP_USER}:${APP_USER}" "${APP_BASE}"

USER ${APP_USER}
WORKDIR ${APP_ROOT}

COPY --chown="${APP_USER}:${APP_USER}" --from=build /build/lib   ${APP_LIBS}
COPY --chown="${APP_USER}:${APP_USER}"              ./${APP_RELATIVE_PATH}/*.py .

COPY --chown="${APP_USER}:${APP_USER}" ./oasst-shared /tmp/lib/oasst-shared

USER root
RUN --mount=type=cache,target=/var/cache/pip \
    pip install                  \
      --cache-dir=/var/cache/pip \
      --target="${APP_LIBS}"     \
      /tmp/lib/oasst-shared && \
    rm -rf /tmp/lib/oasst-shared
USER ${APP_USER}

COPY --chown="${APP_USER}:${APP_USER}" ./inference/safety/safety_main.sh /entrypoint.sh

CMD ["/entrypoint.sh"]
