#!/usr/bin/env groovy

node {
    stage('checkout') {
        checkout scm
    }

    stage('check java') {
        sh "java -version"
    }

<%_ if (buildTool === 'maven') { _%>
    stage('clean') {
        sh "./mvnw clean"
    }

    <%_ if (applicationType !== 'microservice') { _%>
        <%_ if (clientPackageManager === 'yarn') { _%>
    stage('install tools') {
        sh "./mvnw com.github.eirslett:frontend-maven-plugin:install-node-and-yarn -DnodeVersion=v6.9.4 -DyarnVersion=v0.19.1"
    }

    stage('yarn install') {
        sh "./mvnw com.github.eirslett:frontend-maven-plugin:yarn"
    }
        <%_ } else if (clientPackageManager === 'npm') { _%>
    stage('install tools') {
        sh "./mvnw com.github.eirslett:frontend-maven-plugin:install-node-and-npm -DnodeVersion=v6.9.4 -DnpmVersion=3.10.9"
    }

    stage('npm install') {
        sh "./mvnw com.github.eirslett:frontend-maven-plugin:npm"
    }

        <%_ } _%>
    <%_ } _%>
    stage('backend tests') {
        try {
            sh "./mvnw test"
        } catch(err) {
            throw err
        } finally {
            junit '**/target/surefire-reports/TEST-*.xml'
        }
    }

    <%_ if (applicationType !== 'microservice') { _%>
    stage('frontend tests') {
        try {
            sh "./mvnw com.github.eirslett:frontend-maven-plugin:gulp -Dfrontend.gulp.arguments=test"
        } catch(err) {
            throw err
        } finally {
            junit '**/target/test-results/karma/TESTS-*.xml'
        }
    }

    <%_ } _%>
    stage('packaging') {
        sh "./mvnw package -Pprod -DskipTests"
        archiveArtifacts artifacts: '**/target/*.war', fingerprint: true
    }

<%_ } else if (buildTool === 'gradle') { _%>
    stage('clean') {
        sh "./gradlew clean"
    }

    <%_ if (applicationType !== 'microservice') { _%>
    stage('npm install') {
        sh "./gradlew npmInstall -PnodeInstall"
    }

    <%_ } _%>
    stage('backend tests') {
        try {
            sh "./gradlew test -PnodeInstall"
        } catch(err) {
            throw err
        } finally {
            junit '**/build/**/TEST-*.xml'
        }
    }

    <%_ if (applicationType !== 'microservice') { _%>
    stage('frontend tests') {
        try {
            sh "./gradlew gulp_test -PnodeInstall"
        } catch(err) {
            throw err
        } finally {
            junit '**/build/test-results/karma/TESTS-*.xml'
        }
    }

    <%_ } _%>
    stage('packaging') {
        sh "./gradlew bootRepackage -x test -Pprod -PnodeInstall"
        archiveArtifacts artifacts: '**/build/*.war', fingerprint: true
    }

<%_ } _%>
    // Uncomment the following block to add Sonar analysis.
    /*stage('quality analysis') {
        withSonarQubeEnv('Sonar Server') {
<%_ if (buildTool === 'maven') { _%>
            sh "./mvnw sonar:sonar"
<%_ } else if (buildTool === 'gradle' ) { _%>
            sh "./gradlew sonarqube"
<%_ } _%>
        }
    }*/

}
