@Library('jenkins-pipeline-shared-libraries')_

pipeline {
    agent {
        label 'kie-rhel7 && kie-mem24g && !master'
    }
    tools {
        maven 'kie-maven-3.6.0'
        jdk 'kie-jdk1.8'
    }
    options {
        buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10')
        timeout(time: 600, unit: 'MINUTES')
    }
    stages {
        stage('Kill concurrent builds') {
            steps {
                script {
                    def buildNumber = env.BUILD_NUMBER as int
                    if (buildNumber > 1) milestone(buildNumber - 1)
                    milestone(buildNumber)
                }
            }
        }
        stage('Initialize') {
            steps {
                sh 'printenv'

            }
        }
        stage('Build community projects') {
            steps {
                script {
                    dir("community-projects") {
                        env.CHANGE_AUTHOR = env.CHANGE_AUTHOR ?: env.ghprbPullAuthorLogin ?: 'kiegroup'
                        env.CHANGE_BRANCH = env.CHANGE_BRANCH ?: env.ghprbSourceBranch ?: env.GIT_BRANCH
                        env.CHANGE_TARGET = env.CHANGE_TARGET ?: env.ghprbTargetBranch ?: env.GIT_BRANCH                     
                        githubscm.checkoutIfExists('droolsjbpm-build-bootstrap', "${env.CHANGE_AUTHOR}", "${env.CHANGE_BRANCH}", 'kiegroup', "${env.CHANGE_TARGET}")
                        final REPOSITORY_LIST_FILE = "./script/repository-list.txt"
                        final SETTINGS_XML_ID = "771ff52a-a8b4-40e6-9b22-d54c7314aa1e"
                        configFileProvider([configFile(fileId: SETTINGS_XML_ID, variable: 'MAVEN_SETTINGS_XML_DOWNSTREAM')]) {
                            println "Reading file ${REPOSITORY_LIST_FILE}"
                            def file = readFile REPOSITORY_LIST_FILE
                            def projectCollection = file.readLines()
                            projectCollection.removeAll { 'kie-wb-distributions'.equals(it.toLowerCase()) }
                            treebuild.build(projectCollection, "${SETTINGS_XML_ID}", '-e -nsu -Pbusiness-central,wildfly,sourcemaps,no-showcase clean install -Dfull=true -Dproductized=true -Dcontainer=wildfly -Dcontainer.profile=wildfly -Dmaven.test.failure.ignore=true -Drevapi.skip=true -Denforcer.skip=true -Dmaven.test.redirectTestOutputToFile=true -Dgwt.compiler.localWorkers=1 -Dwebdriver.firefox.bin=/opt/tools/firefox-60esr/firefox-bin', true)
                        }
                    }
                }
            }
        }
        stage('Deploy kie-wb-distributions project prod profile') {
            steps {
                script {
                    dir("community-projects") {
                        println "Building kie-wb-distributions project"
                        treebuild.build(['kie-wb-distributions'], "prod-maven-settings", "clean deploy -Dproductized=true -Dfull -DaltDeploymentRepository=local::default::file://${env.WORKSPACE}/deployDirectory", true)
                    }
                }
            }
        }
        stage('Deploy Production projects') {
            steps {
                script {
                    env.CHANGE_AUTHOR = 'jboss-integration'
                    // This is the map project, variable to store the version from this project
                    configFileProvider([configFile(fileId: "49737697-ebd6-4396-9c22-11f7714808eb", variable: 'PRODUCTION_PROJECT_LIST')]) {
                        println "Reading file ${PRODUCTION_PROJECT_LIST} jenkins file"
                        def projectCollection = readFile "${env.PRODUCTION_PROJECT_LIST}"
                        println "Project collection ${projectCollection}"
                        treebuild.build(projectCollection.readLines(), "prod-maven-settings", "clean deploy -Dproductized=true -DaltDeploymentRepository=local::default::file://${env.WORKSPACE}/deployDirectory")
                    }
                }
            }
        }
        stage('Upload Files to repository') {
            steps {
                script {
                    echo "[INFO] Start uploading ${env.WORKSPACE}/deployDirectory"
                    dir("${env.WORKSPACE}/deployDirectory") {
                        withCredentials([usernameColonPassword(credentialsId: "${env.NIGHTLY_DEPLOYMENT_CREDENTIAL}", variable: 'deploymentCredentials')]) {
                            sh "zip -r deploy ."
                            sh "curl --upload-file deploy.zip -u $deploymentCredentials -v ${RHBA_PROD_DEPLOYMENT_REPO_URL}"
                        }
                    }
                }
            }
        }
    }
    post {
        unstable {
            script {
                mailer.sendEmailFailure()
            }
        }
        failure {
            script {
                mailer.sendEmailFailure()
            }
        }
        always {
            script {
                util.printGitInformationReport()
            }
            echo 'Archiving logs...'
            archiveArtifacts excludes: '**/target/checkstyle.log', artifacts: '**/*.maven.log,**/target/*.log', fingerprint: false, defaultExcludes: true, caseSensitive: true, allowEmptyArchive: true
        }
        cleanup {
            cleanWs()
        }
    }
}
