FROM node:16-alpine AS node_builder

RUN apk add git  # for version info

WORKDIR /app
COPY package*.json /app/
COPY packages/meteoio-ui/package*.json /app/packages/meteoio-ui/
COPY packages/meteoio-platform-client/package*.json /app/packages/meteoio-platform-client/
COPY packages/meteoio-platform-web-pages/package*.json /app/packages/meteoio-platform-web-pages/

RUN npm install
# NOTE: node modules are .dockerignore-d and installed in the previous (cachable) layer
COPY ./ /app/



FROM node_builder AS frontend_build
# RUN npm run generate  # dev, please run this and commit the generated code.
RUN npm run build



FROM squidfunk/mkdocs-material:9 AS mkdocs_build
COPY ./docs /docs/docs
COPY ./mkdocs.yml mkdocs.yml
RUN mkdocs build



FROM nginx:alpine AS server
COPY --from=frontend_build /app/packages/meteoio-platform-web-pages/dist /app/
COPY --from=mkdocs_build /docs/site /app/docs
RUN gzip -k /app/* && gzip -k /app/assets/*
COPY ./nginx.conf /etc/nginx/nginx.conf



FROM python:3.11-slim AS python_base
#RUN apk add git
#RUN apk add strace
#RUN apk add py3-psutil  # gcc python3-dev is not sufficient to build psutil
RUN apt-get update && apt-get install -y strace &&  \
    python -m pip install wheel &&  \
    python -m pip install setuptools --upgrade
# USER appuser
COPY ./server/requirements.txt /app/
WORKDIR /app
RUN python -m pip install -r requirements.txt


FROM python_base AS backend
# RUN python -m pip install -r requirements.txt
COPY ./server /app



FROM python_base AS job_runner
# This build is merging the job_runner on top of a MeteoIO build from sources,
#   so, we do not do `from backend` but we copy the instructions.
# RUN python -m pip install -r requirements.txt
RUN apt-get update &&  \
    apt-get install -y git g++ make cmake libnetcdf-dev libproj-dev curl &&  \
    mkdir -p /root/usr

RUN apt install -y fuse3     sshfs sshpass       davfs2        s3fs     smbnetfs cifs-utils busybox
# davfs2 is for WebDAV FUSE mount, with confirm to allow all users.

# RUN groupadd -g 1000 fuse && useradd -r -u 1000 -g fuse appuser
RUN echo "user_allow_other" >> /etc/fuse.conf

ARG METEOIO_BUILD_BRANCH
ARG METEOIO_BUILD_COMMAND
ENV METEOIO_BUILD_BRANCH="${METEOIO_BUILD_BRANCH}"
ENV METEOIO_BUILD_COMMAND="${METEOIO_BUILD_COMMAND}"
RUN git clone --branch "${METEOIO_BUILD_BRANCH}" https://code.wsl.ch/snow-models/meteoio.git /root/src/meteoio
RUN cd /root/src/meteoio && \
    bash -c "${METEOIO_BUILD_COMMAND}" && \
    make -j 2 && \
    make install

COPY ./server /app



FROM job_runner AS job_runner_lab
RUN pip install jupyterlab



FROM python_base AS backend_with_pywps
# RUN python -m pip install GDAL==1.10.0 --global-option=build_ext --global-option="-I/usr/include/gdal"
RUN apt-get install -y git python3-gdal gunicorn
COPY ./server/requirements_with_pywps.txt /app/
RUN python -m pip install -r requirements_with_pywps.txt
COPY ./server /app
