ARG APP_USER_UID=1000
ARG APP_USER_GID=1000

FROM python:3.12.11-slim-bookworm AS base

ARG APP_USER_UID
ARG APP_USER_GID

ENV PIP_DEFAULT_TIMEOUT=100 \
    PIP_DISABLE_PIP_VERSION_CHECK=on \
    PIP_INDEX_URL="https://nexus.bthlabs.pl/repository/pypi/simple/" \
    PIP_NO_CACHE_DIR=off \
    POETRY_HOME="/srv/poetry" \
    POETRY_NO_INTERACTION=1 \
    POETRY_VERSION=1.8.3 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    VIRTUAL_ENV="/srv/venv" \
    YARN_MODULES_FOLDER="/srv/node_modules" \
    YARN_REGISTRY="https://nexus.bthlabs.pl/repository/npm/"

RUN if [ ! $(getent group ${APP_USER_GID}) ];then groupadd -g ${APP_USER_GID} app; fi && \
    useradd -m -d /home/app -u ${APP_USER_UID} -g ${APP_USER_GID} app && \
    apt-get update && \
    apt-get install --no-install-recommends -y curl iputils-ping less net-tools vim-tiny wget && \
    (curl -sSL https://install.python-poetry.org | python -) && \
    python3.12 -m venv ${VIRTUAL_ENV} && \
    mkdir /srv/app /srv/bin /srv/etc /srv/etc/entrypoint.d/ /srv/lib /srv/local /srv/log /srv/node_modules /srv/opt /srv/packages /srv/run /srv/tmp /srv/uploads

COPY --chown=$APP_USER_UID:$APP_USER_GID base/ops/bin/*.sh /srv/bin/
RUN chown -R ${APP_USER_UID}:${APP_USER_GID} /srv

ENV PATH="${VIRTUAL_ENV}/bin:/srv/bin:/srv/poetry/bin:${PATH}"

USER app
WORKDIR /srv/app

ENTRYPOINT ["/srv/bin/entrypoint.sh"]
CMD ["echo", "NOOP"]

FROM base AS build-python

ARG APP_USER_UID
ARG APP_USER_GID
ARG IMAGE_ARCH

USER root
RUN MACHINE=$(uname -m) && \
    case "${MACHINE}" in \
        x86_64 | amd64)   IMAGE_ARCH="amd64" ;; \
        aarch64 | arm64)  IMAGE_ARCH="arm64" ;; \
        *) echo "Unsupported machime: ${MACHINE}" >&2; exit 1 ;; \
    esac && \
    apt-get update && \
    apt-get install --no-install-recommends -y build-essential inotify-tools wait-for-it && \
    (mkdir /srv/tmp/minify; cd /srv/tmp/minify; wget -O minify.tar.gz https://github.com/tdewolff/minify/releases/download/v2.23.11/minify_linux_${IMAGE_ARCH}.tar.gz; tar xvf minify.tar.gz; mv minify /srv/bin; cd /srv/app; rm -rf /srv/tmp/minify) && \
    chown -R ${APP_USER_UID}:${APP_USER_GID} /srv

USER app

FROM build-python AS build-node

ARG APP_USER_UID
ARG APP_USER_GID
ARG NODE_ARCH

USER root
RUN MACHINE=$(uname -m) && \
    case "${MACHINE}" in \
        x86_64 | amd64)   NODE_ARCH="x64" ;; \
        aarch64 | arm64)  NODE_ARCH="arm64" ;; \
        *) echo "Unsupported arch: $arch" >&2; exit 1 ;; \
    esac && \
    wget -O /srv/tmp/node.tar.xz https://nodejs.org/download/release/v22.14.0/node-v22.14.0-linux-${NODE_ARCH}.tar.xz && \
    tar xvf /srv/tmp/node.tar.xz -C /srv/opt && \
    rm -f /srv/tmp/node.tar.xz && \
    mv /srv/opt/node-v22.14.0-linux-${NODE_ARCH} /srv/opt/node

ENV PATH="/srv/opt/node/bin:${PATH}"

RUN npm install -g yarn@1.22.22 && \
    chown -R ${APP_USER_UID}:${APP_USER_GID} /srv

USER app
