FROM node:18.12-buster as prep

RUN apt-get update && apt-get install -y jq
COPY package.json /tmp

RUN jq '{ dependencies, devDependencies, peerDependencies, scripts: (.scripts | { postinstall }) }' < /tmp/package.json > /tmp/deps.json
# keep postinstall script

### STAGE 1: Build ###

# We label our stage as ‘builder’
FROM node:18.12-buster as builder

COPY --from=prep /tmp/deps.json ./package.json
COPY yarn.lock ./

## Storing node modules on a separate layer will prevent unnecessary npm installs at each build
RUN yarn install && mkdir /ng-app && mv ./node_modules ./ng-app
ARG bamboo_sonarqube_api_token_secret
ENV bamboo_sonarqube_api_token_secret=$bamboo_sonarqube_api_token_secret

WORKDIR /ng-app

COPY apps apps
COPY libs libs
COPY tools tools
COPY package.json package.json
COPY yarn.lock yarn.lock
COPY angular.json angular.json
COPY nx.json nx.json
COPY .eslintrc.json .eslintrc.json
COPY tsconfig.json tsconfig.json
COPY versions.sh version.sh
COPY paligo-styles paligo-styles
COPY sonar.js sonar.js

## Build the angular app in production mode and store the artifacts in dist folder
RUN node sonar.js
RUN yarn run build-lint-all
RUN yarn run build-paligo-styles

CMD ["/bin/cp", "-r", "/ng-app/dist/paligo-styles", "/tmp/styles-export"]

### STAGE 2: Setup ###


FROM nginx:1.21.4-alpine
RUN apk add --update nano && rm -rf /var/cache/apk/*

## Copy our default nginx config
COPY docker/common/nginx/nginx.conf /etc/nginx/conf.d/default.conf

## Remove default nginx website
RUN rm -rf /usr/share/nginx/html/*

## From ‘builder’ stage copy over the artifacts in dist folder to default nginx public folder
COPY --from=builder /ng-app/dist/apps/red-ui /usr/share/nginx/html/ui
RUN chmod o+r -R /usr/share/nginx/html
RUN chmod g+r -R /usr/share/nginx/html

## Change permissions to enable openShift functionality
RUN chmod -R g+rwx /var/cache/nginx /var/run /var/log/nginx /usr/share /etc/nginx

USER 1001

COPY docker/red-ui/docker-entrypoint.sh /
CMD ["/docker-entrypoint.sh"]
