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

# pull official base image
FROM python:3.8-slim-buster as builder

# update system
RUN apt-get update && \
    apt-get install -y --no-install-recommends build-essential && \
    apt-get clean

# set working directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

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

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

# pull official base image
FROM python:3.8-slim-buster

# create home directory and app user
RUN mkdir -p /home/app && \
    addgroup --system app && \
    adduser --system --group app

# create appropriate directories
ENV APP_HOME=/home/app
ENV APP_DATA=/home/app/data
RUN mkdir -p ${APP_DATA}
WORKDIR ${APP_HOME}

# copy and install packages from builder
COPY --from=builder /usr/src/app/wheels /wheels
COPY --from=builder /usr/src/app/requirements.txt requirements.txt
RUN pip install --no-cache /wheels/*

# add app
COPY ./code .

# change ownership to app user
RUN chown -R app:app ${APP_HOME}

# change to the app user
USER app

ENTRYPOINT ["python", "main.py"]