###########
# BUILDER #
###########

# pull official base image
FROM python:3.11-slim AS builder

# set work directory
WORKDIR /app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install system dependencies
RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# lint
RUN pip install --upgrade pip
COPY . /app/

# install python dependencies
COPY ./requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /app/wheels -r requirements.txt


#########
# FINAL #
#########

# pull official base image
FROM python:3.11-slim

# create directory for the app user
RUN mkdir -p /home/app

# create the app user
RUN addgroup --system app && adduser --system --group app

# create the appropriate directories
RUN mkdir -p /home/app/api/staticfiles
RUN chmod -R 777 /home/app/api/staticfiles
WORKDIR /home/app/api

# install dependencies
RUN apt-get update && \
    apt-get install -y --no-install-recommends netcat-openbsd && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/wheels /wheels
COPY --from=builder /app/requirements.txt .
RUN pip install --upgrade pip
RUN pip install --no-cache /wheels/*

# copy entrypoint.prod.sh
COPY ./entrypoint.prod.sh .
RUN sed -i 's/\r$//g'  /home/app/api/entrypoint.prod.sh
RUN chmod +x  /home/app/api/entrypoint.prod.sh

# copy project
COPY . /home/app/api

# chown all the files to the app user
RUN chown -R app:app /home/app/api

# change to the app user
USER app

# run entrypoint.prod.sh
ENTRYPOINT ["/home/app/api/entrypoint.prod.sh"]