ARG product_version=7.5.1
ARG build_number=1
ARG oo_root='/var/www/onlyoffice/documentserver'
ARG build_deps="git make g++ bzip2 python3-dev python3-pip nodejs npm"

## Setup
FROM onlyoffice/documentserver:${product_version}.${build_number} as setup-stage
ARG product_version
ARG build_number
ARG oo_root
ARG build_deps

ENV PRODUCT_VERSION=${product_version}
ENV BUILD_NUMBER=${build_number}

WORKDIR /build

RUN apt-get update && \
    apt-get install -y ${build_deps} && \
    npm install -g pkg grunt grunt-cli && \
    rm -rf /var/lib/apt/lists/*

## Clone
FROM setup-stage as clone-stage
ARG tag=v${PRODUCT_VERSION}.${BUILD_NUMBER}

RUN git clone --quiet --branch $tag --depth 1 https://github.com/ONLYOFFICE/build_tools.git /build/build_tools
RUN git clone --quiet --branch $tag --depth 1 https://github.com/ONLYOFFICE/server.git      /build/server

## Build
FROM clone-stage as build-stage

COPY config/server.patch /build/server.patch
RUN cd /build/server && \
    git apply --ignore-space-change --ignore-whitespace /build/server.patch

# build server with license checks patched
WORKDIR /build/server
RUN make
RUN pkg /build/build_tools/out/linux_64/onlyoffice/documentserver/server/FileConverter --targets=node16-linux -o /build/converter
RUN pkg /build/build_tools/out/linux_64/onlyoffice/documentserver/server/DocService --targets=node16-linux --options max_old_space_size=4096 -o /build/docservice

RUN grunt

## Final image
FROM onlyoffice/documentserver:${product_version}.${build_number} as image-stage
ARG oo_root

#server
COPY --from=build-stage /build/converter  ${oo_root}/server/FileConverter/converter
COPY --from=build-stage /build/docservice ${oo_root}/server/DocService/docservice

RUN apt-get update && \
    apt-get install -y python3-dev python3-pip && \
    pip install PyCryptodome

COPY config/license.py /license/license.py
COPY config/license.sh /license/license.sh
