node {

	echo "<======================================="
	echo "JENKINS_HOME: ${env.JENKINS_HOME}"
	echo "JOB_NAME: ${env.JOB_NAME}"
	echo "BRANCH: ${env.BRANCH_NAME}"
	echo "=======================================>"

	def sonarScannerHome = tool name: 'default', type: 'hudson.plugins.sonar.SonarRunnerInstallation'

	env.PATH = "${sonarScannerHome}/bin:${env.PATH}"

	stage ("Init") {
		deleteDir()
		checkout scm

		env.PROJECT_VERSION = sh (
			script: "node -pe \"require('./package').version\"",
			returnStdout: true
		).trim()
	}

	stage("Install Dependencies") {
		parallel "Install node modules":{
			sh "npm install"
		}, "Install bower components":{
			sh "bower update --force-latest --allow-root"
		}
	}

	stage ("Test") {
		def TEST_PASSED = sh (
			set: "+x",
			script: "xvfb-run -a npm test --silent",
			returnStatus: true
		) == 0

		if (!TEST_PASSED) {
			currentBuild.result = "UNSTABLE"

			node {
				flowdockMsg = "${env.JOB_NAME} tests failed.  Build is unstable. Please take a look at: ${env.BUILD_URL}console"
					build job: 'notification', parameters: [[$class: 'StringParameterValue', name: 'MESSAGE', value: flowdockMsg]]
			}

		} else {
			stash includes: "coverage/lcov-report/**", name: "coverage"
			//stash includes: "dist/lint/**", name: "lint"
		}
	}

	stage ("Build") {
		parallel "Build": {
			sh "npm run dist"
			archive (includes: "dist/**/*.zip")

		}, "SAST": {
			withSonarQubeEnv("sonar-jenkins server") {
				// expects to find a file called sonar-project.properties
				echo "doing sonarqube stuff for ${currentBuild.displayName}:${env.BRANCH_NAME}@${env.PROJECT_VERSION}"
				sh "${sonarScannerHome}/bin/sonar-scanner -Dsonar.projectVersion=${env.PROJECT_VERSION}  -Dsonar.branch=${env.BRANCH_NAME}"
			}
		}, "Test:Functional": {
			echo "Nothing here yet."
		}

	}

	stage ("Cleanup") {
		step([$class: 'WsCleanup'])
	}

}

