pipeline {
	agent {
        kubernetes {
            yamlFile 'jenkins/kubernetesPod.yaml'
        }
    }

    environment {
        SONAR_KEY = "#GIT-REPO-NAME#"
        SONAR_URL = "https://sonarqube.cloud.digite.com"
        SONAR_EXCLUDE_FILES_LIST = "**/test/**,**/build/**"
        BRANCH_BASE_NAME = "${env.GIT_BRANCH}".tokenize('/').last()
        MODULE_NAME = "#GIT-REPO-NAME#"
        PRODUCT_NAME = "#GIT-REPO-NAME#"
        ELK_INDEX_NAME = "node-app#GIT-REPO-NAME#-be-jest"
        ELK_HOST= "espy.digite.com"
        ELK_PORT= 9200
    }

	stages {
		stage('Dependencies Install') {
			steps {   
                script {
                    FAILED_STAGE = env.STAGE_NAME
                }

			    container('node-js') {
			        withCredentials([
                        usernamePassword(
                            credentialsId: 'dc-gitlab-creds',
                            usernameVariable: 'USERNAME',
                            passwordVariable: 'PASSWORD'
                        ), 
                        string(credentialsId: 'nexus-npm-repo-token', variable: 'NEXUS_TOKEN')
                    ]) {
                        sh 'sed -i "s/<auth_token>/${NEXUS_TOKEN}/g" .npmrc'
                        sh 'npm cache clean --force'
                        sh 'npm install'
                        sh 'npm install --save-dev jest-junit'
			        }
				}
			}
		}

		stage('Unit Automation') {
			steps {   
                script {
                    FAILED_STAGE = env.STAGE_NAME
                }

			    container('node-js') {
				    sh 'npm run test:coverage --testResultsProcessor="jest-junit"'
			    }
			}
		}

		stage('Sonar Scan') {
			steps {
                script {
                    FAILED_STAGE = env.STAGE_NAME
                }

                container('node-js') {
                    withCredentials([string(credentialsId: 'sonar_login_token', variable: 'SONAR_LOGIN')]) { //set SECRET with the credential content
                        withSonarQubeEnv('SonarQube Cloud Server') { 
                            sh 'node_modules/sonarqube-scanner/dist/bin/sonar-scanner -Dsonar.projectKey=${SONAR_KEY} -Dsonar.projectName=${SONAR_KEY}-${BRANCH_BASE_NAME} -Dsonar.sources=./src/function -Dsonar.host.url=${SONAR_URL} -Dsonar.login=${SONAR_LOGIN} -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info -Dsonar.exclusions=${SONAR_EXCLUDE_FILES_LIST}'
                        }
                    }

                    timeout(time: 5, unit: 'MINUTES') {
                        waitForQualityGate abortPipeline: true
                    }  
				}
            }
		}

        stage ('Docker Image && Nexus Publish') {
            steps {
                script {
                    FAILED_STAGE = env.STAGE_NAME
                }

                script {
                    def packageJSON = readJSON file: 'package.json'
                    def packageJSONVersion = packageJSON.version

                    echo packageJSONVersion

                    container('build-image') {
                        script {
                            withCredentials([string(credentialsId: 'digite-docker-repo-creds', variable: 'docker_login')]) { //set SECRET with the credential content
                                sh 'mkdir -p /kaniko/.docker'
                                sh 'echo {\\"auths\\":{\\"${Nexus_Docker_URL}\\":{\\"auth\\":\\"${docker_login}\\"}}} > /kaniko/.docker/config.json'
                                sh "/kaniko/executor -f Dockerfile --context `pwd` --cache=true --destination docker.cloud.digite.com/auth-fabric/hagrid:${packageJSONVersion}"
                                sh "/kaniko/executor -f Dockerfile --context `pwd` --cache=true --destination docker.cloud.digite.com/auth-fabric/hagrid:${BRANCH_BASE_NAME}-latest"
                            }
                        }
                    }
                }
            }
        }
    }

    post {
        failure {
            googlechatnotification url: "${Swiftalk_Chat_URL}",
                message: "OnCommit pipeline of job ${env.JOB_NAME} for build ${env.BUILD_NUMBER} is failed - ${env.BUILD_URL}console at stage `${FAILED_STAGE}`"
        }
        fixed {
            googlechatnotification url: "${Swiftalk_Chat_URL}",
                message: "OnCommit pipeline of job ${env.JOB_NAME} in build ${env.BUILD_NUMBER} is fixed - ${env.BUILD_URL}console"
        }
    }
}
