pipeline {
    agent any

    environment {
        VERSION = VersionNumber([
            versionNumberString: 
                '${BUILDS_ALL_TIME}',
            versionPrefix: '1.0.',
            worstResultForIncrement: 'SUCCESS'
        ])
        publish = 0
    }

    stages {
        stage('Setup') {
            steps {
                echo 'Setting up test environment'
                sh 'npm ci'
                sh 'nodejs jenkins.js ${VERSION}'
                script {
                    currentBuild.displayName = env.VERSION
                }
            }
        }
        stage('Testing') {
            steps {
                echo 'Running tests...'
                sh 'npm test'
            }
        }
    }
    post {
        success {
            script {
                publish = sh script: "git log -1 | grep '\\[no publish\\]'", returnStatus: true
                if (publish != 0) {
                  echo 'Deploying'
                  sh 'npm publish'   
                } else {
                  echo 'Build successful, Commit not marked for deploying'
                  currentBuild.result = "UNSTABLE"
                }
            }
        }
    }
}