FROM ${buildRegistry}/build/node:${version}-slim-secure-multiarch_v2.0 as build-env

WORKDIR /usr/src/app

COPY id_github_jenkins /root/.ssh/id_rsa

RUN ssh-keyscan github.com >> /root/.ssh/known_hosts

COPY . ./
<% add_files.each { print "COPY ${it.path} ${it.target}\n" } %>

RUN ls -al && \
    echo 'NPM Install...' && \
    <% if (npm_install_arg) { %>\
        echo 'Using custom npm install command: ${npm_install_arg}' && \
        ${npm_install_arg} && \
    <% } else { %>\
        npm ci && \
    <% } %>\
    echo 'Ensuring .npmrc is available in subdirectories...' && \
    for subdir in server client; do \
        if [ -d "\$subdir" ] && [ -f .npmrc ] && [ ! -f "\$subdir/.npmrc" ]; then \
            cp -v .npmrc "\$subdir/.npmrc"; \
        fi; \
    done && \
    <% if (pbac_enabled) { %>\
        echo 'Installing PBAC Registry Sync CLI...' && \
        git config --global url."git@github.com:".insteadOf "https://github.com/" && \
        npm install -g pbac-registry-sync-cli --registry=${npm_registry} && \
        echo 'Syncing PBAC Registry for scope: ${pbac_scope_name} environment: ${pbac_env}' && \
        sync-pbac-registry ${pbac_scope_name} ${pbac_env} && \
        echo 'PBAC Registry Sync Completed' && \
        echo 'Copying .npmrc to subdirectories for proper registry resolution...' && \
        for subdir in server client; do \
            if [ -d "\$subdir" ] && [ ! -f "\$subdir/.npmrc" ]; then \
                cp -v .npmrc "\$subdir/.npmrc"; \
            fi; \
        done && \
    <% } %>\
    if ! ${skip_sonar}; then \
        cat .env | grep 'SONAR_' && \
        echo 'Installing Java 17...' && \
        if [ "\$(cat /etc/os-release | grep 'ID=' | awk -F= '{print \$2}' | sed '2d')" = 'alpine' ]; then \
            echo "Alpine" && \
            apk add --no-cache openjdk17; \
        else \
            echo "Debian" && \
            apt-get update && \
            apt-get install -y --no-install-recommends openjdk-17-jre && \
            apt-get clean; \
        fi && \
        echo 'Performing Test Coverage...' && \
        npm run ${testCMD} || true && \
        echo 'Static Analysis...' && \
        npm run sonar -- source=${scmType}; \
    fi && \
    echo 'NPM build...' && \
    npm run build
