# `python-base` sets up all our shared environment variables
FROM python:3.8-slim as python-base

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=off \
    PIP_DISABLE_PIP_VERSION_CHECK=on \
    PIP_DEFAULT_TIMEOUT=100 \
    POETRY_VERSION=1.1.8 \
    POETRY_HOME="/opt/poetry" \
    POETRY_VIRTUALENVS_IN_PROJECT=true \
    POETRY_NO_INTERACTION=1 \
    PYSETUP_PATH="/opt/pysetup" \
    VENV_PATH="/opt/pysetup/.venv"

ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH"


# `builder-base` stage is used to build deps + create our virtual environment
FROM python-base as builder-base
RUN apt-get update \
    && apt-get install --no-install-recommends -y \
        curl \
        build-essential

RUN curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python

WORKDIR $PYSETUP_PATH
COPY poetry.lock pyproject.toml ./

RUN poetry install --no-root


# `production` image used for runtime
FROM python-base

ARG DBMATE_VERSION=1.12.0

RUN apt-get update && apt-get install -y build-essential cron curl wget postgresql-client

RUN wget -q https://github.com/amacneil/dbmate/releases/download/v$DBMATE_VERSION/dbmate-linux-amd64 \
  && mv dbmate-linux-amd64 /usr/local/bin/dbmate \
  && chmod +x /usr/local/bin/dbmate

COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH
COPY entrypoint.py /
RUN chmod +x /entrypoint.py

RUN mkdir /tmp/prometheus && chmod +x /tmp/prometheus
ENV prometheus_multiproc_dir /tmp/prometheus

COPY . /app/
WORKDIR /app

RUN crontab /app/crontab.txt

ENV PYTHONPATH=.

EXPOSE 12345

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