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

# pull official base image
FROM python:3.10-alpine3.14 as builder

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install libraries dependencies
RUN apk update \
    && apk add postgresql-dev gcc python3-dev musl-dev git zlib-dev jpeg-dev \
    wkhtmltopdf xvfb ttf-dejavu ttf-droid ttf-freefont ttf-liberation

# lint
RUN pip install --upgrade pip
# RUN pip install flake8==3.9.2
# COPY . .
# RUN flake8 --ignore=E501,F401 .

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

COPY . .

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

# pull official base image
FROM python:3.10-alpine3.14

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

# create the app user
RUN addgroup -S app && adduser -S app -G app

# create the appropriate directories
ENV HOME=/home/app
ENV APP_HOME=/home/app/web
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

# install dependencies
RUN apk update && apk add libpq gcc python3-dev musl-dev zlib-dev jpeg-dev \
    wkhtmltopdf xvfb ttf-dejavu ttf-droid ttf-freefont ttf-liberation
COPY --from=builder /usr/src/app/wheels /wheels
COPY --from=builder /usr/src/app/requirements/production.pip .
RUN pip install --no-cache /wheels/*


# copy entrypoint.sh
COPY ./entrypoint.sh .

COPY . $APP_HOME

# copy entrypoint.sh znovu, nebo jen nastavíme práva TEĎ
# Zde se ujistěte, že je entrypoint.sh ošetřen proti CRLF a má +x.

# Odstranění CRLF znaků (pouze u entrypoint.sh, pokud je kopírován na *nix)
RUN sed -i 's/\r$//g' $APP_HOME/entrypoint.sh

# NASTAVENÍ OPRÁVNĚNÍ KE SPUŠTĚNÍ - HNED PŘED ENTRYPOINTEM
RUN chmod +x $APP_HOME/entrypoint.sh

# chown all the files to the app user
# Toto je nutné, pokud ENTRYPOINT spustíte jako USER app
RUN chown -R app:app $APP_HOME

# chown all the files to the app user
# RUN chown -R app:app $APP_HOME

# change to the app user - TODO resolve permission error when creating cron
# USER app

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