# node image
FROM node:21-alpine3.18 as compiled
WORKDIR /tmp 
USER root

# Copy the source code into the temp folder.
COPY . /tmp

# Installing the dependencies required for compiling.
RUN yarn install && yarn global add typescript

# Compile the project FROM typescript INTO javascript
RUN tsc

# Putting some stuff into the final build
RUN cp -r /tmp/*.json /tmp/build/ && \
    cp -r /tmp/data.template /tmp/build/ && \
    cp -r /tmp/src/views /tmp/build/src/ && \
    cp -r /tmp/data.template /tmp/build && \
    cp -r /tmp/scripts/docker_bootstrapper.sh /tmp/build/bootstrapper.sh && \
    cp -r /tmp/scripts/docker_run.sh /tmp/build/runner.sh

# The final version of disseminate is now in /tmp/build

FROM node:21-alpine3.18 as main_image

# Create a volume for our data folder
VOLUME ["/app/data"]

# Create a directory for our new app.
RUN mkdir -p /app

# Switch to the directory.
WORKDIR /app

# Delete default node user for the next step.
RUN deluser node

# We want to run disseminate as a non-root user.
ARG UID=1000
ARG GID=1000
RUN addgroup -g $GID disseminate && \
    adduser --home /app --uid $UID -G disseminate --disabled-password disseminate

# Give our non-root user access to /app
RUN chown -R disseminate:disseminate /app

# Installing bash, mostly for debugging.
RUN apk add bash

# Switching to non-root user.
USER disseminate

# Copying the compiled project into our main image, ownership of the build is set to our aforementioned (non-root) user.
COPY --chown=$UID:$GID --from=compiled /tmp/build/ /app

# Installing the dependencies.
RUN yarn install --production

# Startup command
CMD ["npm", "run", "docker:prod:bootstrapper"]