# The tag here should match the Meteor version of your app, per .meteor/release
FROM geoffreybooth/meteor-base:2.4

# Copy app package.json and package-lock.json into container
COPY ./package*.json $APP_SOURCE_FOLDER/

ENV TOOL_NODE_FLAGS="--max-old-space-size=4096"

RUN bash $SCRIPTS_FOLDER/build-app-npm-dependencies.sh

# Copy app source into container
COPY . $APP_SOURCE_FOLDER/

WORKDIR $APP_SOURCE_FOLDER
RUN meteor npm run build; exit 0
RUN bash $SCRIPTS_FOLDER/build-meteor-bundle.sh


# Use the specific version of Node expected by your Meteor release, per https://docs.meteor.com/changelog.html; this is expected for Meteor 1.11.1
FROM node:14.18.1-alpine

ENV APP_BUNDLE_FOLDER /opt/bundle
ENV SCRIPTS_FOLDER /docker

# Install OS build dependencies, which stay with this intermediate image but don’t become part of the final published image
RUN apk --no-cache add \
	bash \
	g++ \
	make \
	python3

# Copy in entrypoint
COPY --from=0 $SCRIPTS_FOLDER $SCRIPTS_FOLDER/

# Copy in app bundle
COPY --from=0 $APP_BUNDLE_FOLDER/bundle $APP_BUNDLE_FOLDER/bundle/

# Remove sharp so it rebuilds for the kernel on this alpine image
RUN rm -rf $APP_BUNDLE_FOLDER/bundle/programs/server/npm/node_modules/sharp/vendor/

RUN bash $SCRIPTS_FOLDER/build-meteor-npm-dependencies.sh --build-from-source
#RUN printf "\n[-] Installing Meteor application server NPM dependencies...\n\n"
#WORKDIR $APP_BUNDLE_FOLDER/bundle/programs/server/
#RUN ls -la
#RUN cat package.json
#RUN npm install
#RUN npm rebuild --build-from-source
#WORKDIR $APP_BUNDLE_FOLDER/bundle/programs/server/npm
#RUN npm rebuild --build-from-source


# Start another Docker stage, so that the final image doesn’t contain the layer with the build dependencies
# See previous FROM line; this must match
FROM node:14.18.1-alpine

ENV APP_BUNDLE_FOLDER /opt/bundle
ENV SCRIPTS_FOLDER /docker

# Install OS runtime dependencies
RUN apk --no-cache add \
	nss \
    chromium \
    freetype \
    freetype-dev \
    harfbuzz \
    ttf-freefont \
    yarn \
    g++ \
    make \
    python3 \
    bash \
    ca-certificates

# Tell Puppeteer to skip installing Chrome. We'll be using the installed package from above.
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
    PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser

# Copy in entrypoint with the built and installed dependencies from the previous image
COPY --from=1 $SCRIPTS_FOLDER $SCRIPTS_FOLDER/

# Copy in app bundle with the built and installed dependencies from the previous image
COPY --from=1 $APP_BUNDLE_FOLDER/bundle $APP_BUNDLE_FOLDER/bundle/

RUN tar -czf app.tar.gz -C $APP_BUNDLE_FOLDER/ .

# Start app
ENTRYPOINT ["/docker/entrypoint.sh"]

CMD ["node", "main.js"]
