### STAGE 1 NODEJS BASE IMAGE

FROM debian:trixie-slim AS node-base

ARG NODE_MAJOR=24

# Install general dependencies and nodesource's NodeJS
RUN apt-get update && \
    apt-get install -y --no-install-recommends --no-install-suggests \
        ca-certificates curl gnupg2 jq tzdata wget && \
    mkdir -p /etc/apt/keyrings/ && \
    curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \
    echo "Types: deb \nURIs: https://deb.nodesource.com/node_${NODE_MAJOR}.x/ \nSuites: nodistro \nComponents: main \nSigned-By: /etc/apt/keyrings/nodesource.gpg" > /etc/apt/sources.list.d/nodesource.sources && cat /etc/apt/sources.list.d/nodesource.sources && \
    apt-get update && \
    apt-get install -y --no-install-recommends --no-install-suggests \
        nodejs

### STAGE 2 BUILDING MESHCENTRAL BASICS
FROM node-base AS mesh-compiler

# Any value inside one of the disable ARGs will be accepted.
ARG DISABLE_EXTRACT="yes"
ARG DISABLE_MINIFY="yes"
ARG DISABLE_TRANSLATE="yes"
#    NODE_OPTIONS="--max_old_space_size=4096"
# If your process gets OOM killed, perhaps the above will help.

RUN mkdir -p /opt/meshcentral/meshcentral

WORKDIR /opt/meshcentral
COPY ./ /opt/meshcentral/meshcentral/

# Check the Docker build arguments and if they are empty do the task.
RUN if [ -n "$DISABLE_EXTRACT" ] || [ -n "$DISABLE_MINIFY" ] || [ -n "$DISABLE_TRANSLATE" ]; then \
        echo "----------\nPREPARING ENVIRONMENT...\n----------"; \
        cd meshcentral && \
        npm install html-minifier-terser@7.2.0 jsdom@26.0.0 esprima@4.0.1 && \
        cd translate && \
        case "$DISABLE_EXTRACT" in \
            false|no|FALSE|NO) \
                echo "----------\nSTARTING THE EXTRACTING PROCESS...\n----------"; \
                node translate.js extractall;; \
            *) \
                echo "Setting EXTRACT as disabled.";; \
        esac && \
        case "$DISABLE_MINIFY" in \
            false|no|FALSE|NO) \
                echo "----------\nSTARTING THE MINIFYING PROCESS...\n----------"; \
                node translate.js minifyall;; \
            *) \
                echo "Setting MINIFY as disabled.";; \
        esac && \
        case "$DISABLE_TRANSLATE" in \
            false|no|FALSE|NO) \
                echo "----------\nSTARTING THE TRANSLATING PROCESS...\n----------"; \
                node translate.js translateall;; \
            *) \
                echo "Setting TRANSLATE as disabled.";; \
        esac; \
        npm uninstall html-minifier-terser jsdom esprima; \
    fi
# Possible more updated alternative? @minify-html/node@0.15.0 -> https://www.npmjs.com/package/@minify-html/node

RUN rm -rf /opt/meshcentral/meshcentral/docker /opt/meshcentral/meshcentral/node_modules /opt/meshcentral/meshcentral/docs

### STAGE 3 PRECOMPILE NODEJS DEPENDENCIES

FROM node-base AS dep-compiler

ENV NODE_ENV="production"

RUN apt-get update && \
    apt-get install -y --no-install-recommends --no-install-suggests \
        gcc g++ make python3

COPY --from=mesh-compiler /opt/meshcentral/meshcentral /opt/meshcentral/meshcentral
WORKDIR /opt/meshcentral/meshcentral

RUN jq '.dependencies += {"modern-syslog": "1.2.0", "telegram": "2.26.22"}' package.json > temp.json && mv temp.json package.json \
    && npm install --package-lock-only \
    && npm ci --omit=dev \
    && npm cache clean --force

### STAGE 4 COMPILING MONGODB TOOLS AND DEPENDENCIES

FROM golang:trixie AS mongo-compiler

ARG INCLUDE_MONGODB_TOOLS="false"

# where build deps are installed for mongo-tools compilation
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential git lsb-release pkg-config libkrb5-dev \
    && rm -rf /var/lib/apt/lists/*

RUN case "$INCLUDE_MONGODB_TOOLS" in \
        true|yes|TRUE|YES) \
            git clone https://github.com/mongodb/mongo-tools /mongo-tools; \
            cd /mongo-tools; \
            ./make build -pkgs=mongodump,mongorestore;; \
        false|no|FALSE|NO) \
            echo "Not building MongoDB Tools from source, what a shame!"; \
            mkdir -p /mongo-tools/bin;; \
        *) \
            echo "Invalid value for build argument INCLUDE_MONGODB_TOOLS, possible values: 'yes', 'true', 'no' or 'false'"; \
            exit 1;; \
    esac

### STAGE 5 COMPILING LAYERS AND FORGING MESHCENTRAL STATE

FROM node-base AS finalizer

# Copy files from previous layers
COPY --from=dep-compiler /opt/meshcentral/meshcentral /opt/meshcentral/meshcentral
COPY --from=mongo-compiler /mongo-tools/bin/ /tmp/bin/

# environment variables
ENV NODE_ENV="production" \
    CONFIG_FILE="/opt/meshcentral/meshcentral-data/config.json" \
    DYNAMIC_CONFIG="false"

# environment variables for the above defined MeshCentral Config.json. Can be done like that following: https://docs.docker.com/reference/dockerfile/#env
ENV ALLOW_PLUGINS="false" \
    ALLOW_NEW_ACCOUNTS="false" \
    ALLOWED_ORIGIN="false" \
    HOSTNAME="localhost" \
    PORT="443" \
    REDIR_PORT="80" \
    INSTALL_STYLISHUI="false" \
    IFRAME="false" \
    LOCAL_SESSION_RECORDING="true" \
    MINIFY="true" \
    REVERSE_PROXY="" \
    REVERSE_PROXY_TLS_PORT="443" \
    REGEN_SESSIONKEY="false" \
    STYLISHUI_FORCE_LATEST="false" \
    WEBRTC="false" \
    TRUSTED_PROXY="" \
    ARGS=""

# Database
# Multi-variable declaration to reduce layers.
ENV USE_MONGODB="false" \
    USE_POSTGRESQL="false" \
    USE_MARIADB="false"

# Preinstallation args one per line due to: https://docs.docker.com/reference/dockerfile/#arg
ARG PREINSTALL_LIBS="false"
ARG INCLUDE_MONGODB_TOOLS="false"
ARG INCLUDE_POSTGRESQL_TOOLS="false"
ARG INCLUDE_MARIADB_TOOLS="false"

# MongoDB Variables
# The following MONGO_URL variable overwrites most other mongoDb related varialbes.
ENV MONGO_HOST="" \
    MONGO_PORT="27017" \
    MONGO_USERNAME="" \
    MONGO_PASS="" \
    MONGO_URL=""

# PostgreSQL Variables
ENV PSQL_HOST="" \
    PSQL_PORT="5432" \
    PSQL_USER="" \
    PSQL_PASS="" \
    PSQL_DATABASE=""

# MariaDB/MySQL Variables.
ENV MARIADB_HOST="" \
    MARIADB_PORT="3306" \
    MARIADB_USER="" \
    MARIADB_PASS="" \
    MARIADB_DATABASE=""

WORKDIR /opt/meshcentral

RUN rm -rfv \
        /var/cache/* \
        /usr/share/man/ \
        /usr/share/doc/ \
        /var/log/* \
        /var/spool/* \
        /var/tmp/* \
        /usr/lib/debug/

RUN case "$PREINSTALL_LIBS" in \
        true|yes|TRUE|YES) \
            cd meshcentral && \
            echo "----------\nPREINSTALLING LIBRARIES...\n----------"; \
            npm install ssh2@1.17.0 nodemailer@6.10.1 image-size@2.0.2 wildleek@2.0.0 yub@0.11.1;; \
        false|no|FALSE|NO) \
            echo "Not pre-installing libraries.";; \
        *) \
            echo "Invalid value for build argument INCLUDE_POSTGRESQL_TOOLS, possible values: 'yes', 'true', 'no' or 'false'"; \
            exit 1;; \
    esac

# NOTE: ALL MODULES MUST HAVE A VERSION NUMBER AND THE VERSION MUST MATCH THAT USED IN meshcentraljs mainStart()
RUN case "$INCLUDE_MONGODB_TOOLS" in \
        true|yes|TRUE|YES) \
            mv /tmp/bin/* /usr/bin; \
            cd meshcentral && \
            echo "----------\nPREINSTALLING MONGODB LIBRARIES...\n----------"; \
            npm install mongodb@4.17.2 @mongodb-js/saslprep@1.3.1;; \
        false|no|FALSE|NO) \
            echo "Not including MongoDB Tools.";; \
        *) \
            echo "Invalid value for build argument INCLUDE_MONGODB_TOOLS, possible values: 'yes', 'true', 'no' or 'false'"; \
            exit 1;; \
    esac

RUN case "$INCLUDE_POSTGRESQL_TOOLS" in \
        true|yes|TRUE|YES) \
            apt-get install -y --no-install-recommends --no-install-suggests postgresql-client-17; \
            cd meshcentral && \
            echo "----------\nPREINSTALLING POSTGRESQL LIBRARIES...\n----------"; \
            npm install pg@8.16.3;; \
        false|no|FALSE|NO) \
            echo "Not including PostgreSQL Tools.";; \
        *) \
            echo "Invalid value for build argument INCLUDE_POSTGRESQL_TOOLS, possible values: 'yes', 'true', 'no' or 'false'"; \
            exit 1;; \
    esac

RUN case "$INCLUDE_MARIADB_TOOLS" in \
        true|yes|TRUE|YES) \
            apt-get install -y --no-install-recommends --no-install-suggests default-mysql-client mariadb-client; \
            cd meshcentral && \
            echo "----------\nPREINSTALLING MARIADB/MYSQL LIBRARIES...\n----------"; \
            npm install mariadb@3.4.5 mysql2@3.15.1;; \
        false|no|FALSE|NO) \
            echo "Not including MariaDB/MySQL Tools.";; \
        *) \
            echo "Invalid value for build argument INCLUDE_MARIADB_TOOLS, possible values: 'yes', 'true', 'no' or 'false'"; \
            exit 1;; \
    esac

# Remove left over files and cache
RUN cd meshcentral \
    && rm -rf /root /tmp/* /var/tmp/* /usr/lib/node_modules/npm/man /usr/lib/node_modules/npm/doc /usr/lib/node_modules/npm/html \
    && npm cache clean --force

# Expose needed ports
EXPOSE ${PORT}
EXPOSE ${REDIR_PORT}

# These volumes will be created by default even without any declaration, this allows default persistence in Docker/Podman. Dummy-proofing.
VOLUME /opt/meshcentral/meshcentral-data
VOLUME /opt/meshcentral/meshcentral-files
VOLUME /opt/meshcentral/meshcentral-web
VOLUME /opt/meshcentral/meshcentral-backups

# Copy images from Git repo, place it before ending so recompilation can make good use of cache.
COPY ./docker/entrypoint.sh  /opt/meshcentral/entrypoint.sh
COPY ./docker/config.json.template /opt/meshcentral/config.json.template

ENTRYPOINT  ["/bin/bash", "/opt/meshcentral/entrypoint.sh"]
