# Define global args
ARG FUNCTION_DIR="/home/app/"
ARG RUNTIME_VERSION
ARG DISTRO_VERSION

# Stage 1 - build function and dependencies
FROM node:${RUNTIME_VERSION}-${DISTRO_VERSION} AS build-image
# Install aws-lambda-cpp build dependencies
RUN apt-get update && \
    apt-get install -y \
        g++ \
        make \
        cmake \
        libcurl4-openssl-dev

# Include global arg in this stage of the build
ARG FUNCTION_DIR
# Create function directory
RUN mkdir -p ${FUNCTION_DIR}

# Copy & build Runtime Interface Client package (as we're installing it from a local filesystem source)
WORKDIR ${FUNCTION_DIR}/deps/aws-lambda-ric
COPY . .

# Node14 uses npm@6.14.18 by default which will downgrade permissions, if it's root,
# before running any build scripts: https://github.com/npm/npm/issues/3497 
# Starting from npm@7.0.0, when npm is run as root, 
# scripts are always run with the effective uid and gid of the working directory owner.
RUN if [ $(node -v | cut -c 1-3) = "v14" ] ; then npm install -g npm@7 ; fi
RUN make build && \
    npm run test:unit

# Copy function code
COPY test/integration/test-handlers/echo/* ${FUNCTION_DIR}
# Install the function's dependencies
WORKDIR ${FUNCTION_DIR}
RUN npm install


# Stage 2 - final runtime image
# Grab a fresh slim copy of the Node image
FROM node:${RUNTIME_VERSION}-${DISTRO_VERSION}-slim

# Required for Node runtimes which use npm@8.6.0+ because
# by default npm writes logs under /home/.npm and Lambda fs is read-only
ENV NPM_CONFIG_CACHE=/tmp/.npm
# Include global arg in this stage of the build
ARG FUNCTION_DIR
# Set working directory to function root directory
WORKDIR ${FUNCTION_DIR}
# Copy in the built dependencies
COPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR}

ENTRYPOINT [ "/usr/local/bin/npx", "aws-lambda-ric" ]
CMD [ "index.handler" ]