//noinspection GroovyAssignabilityCheck
// library annotation should always be followed by underscore
@Library('wfstudio-jenkins-commons') _
pipeline {

    agent {
        label 'windows'
    }

    tools {
        jdk 'JDK8'
        maven 'Maven3.5.0'
    }

    options {
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '10', daysToKeepStr: '60'))
    }

    environment {
        // For credentials env variables *_USR and *_PSW would be created automatically
        // NEXUS_URL and GIT_URL are coming from Global environment variables
        //
        // see https://jenkins.io/doc/book/pipeline/syntax/#environment

        MAVEN_REPO_DIR = "D:\\jenkins\\repos\\${currentBuild.rawBuild.project.parent.displayName}"

        SONAR_AUTH = credentials('sonar_auth')
        BITBUCKET_SONAR_AUTH = credentials('bitbucket_sonar_auth') //To notify Bitbucket form Sonarqube

        NEXUS_URL = 'https://repository.workfusion.com'
        NEXUS_REPO = 'wf-dependencies'
        NEXUS_DEPLOY_AUTH = credentials('repository_deploy')

        SLACK_AUTH_PSW = 'kUxN6XwKWcr0OZTI2k3AGu13'

        S3_BUCKET = 'aa-materials'
    }


    stages {

        stage('Preparations') {
            steps {
                slackMessage buildMessage: "started (${buildCause()})", color: 'lightskyblue', token: SLACK_AUTH_PSW
            }
        }

        stage('Branch or PR build') {
            when {
                not { tag 'release/*' }
            }
            steps {
                failWhen condition: readMavenPom(file: 'odf-bcb\\pom.xml').with {
                    it.version != it.parent.version
                }, message: '\'odf-bcb\' module version should be equal to parent version. Fix inconsistency in pom.xml.'

                buildWithMaven configId: 'odf-maven-settings',
                        goals: [install: { build -> !build.version.endsWith('-SNAPSHOT') || !build.branch.matches(/master|support\/.+/) },
                                deploy : { build -> build.version.endsWith('-SNAPSHOT') && build.branch.matches(/master|support\/.+/) }],
                        options: ['-Pci'],
                        sonar: [login            : SONAR_AUTH_USR,
                                password         : SONAR_AUTH_PSW,
                                bitbucketPassword: BITBUCKET_SONAR_AUTH_PSW,
                                developersEdition: true]
            }
        }

        stage('Release from tag') {
            when {
                tag 'release/*'
            }
            stages {
                stage('Prepare release versions') {
                    steps {
                        shellScript "mvn versions:update-parent -DparentVersion=[${versionToRelease(TAG_NAME)}] -DgenerateBackupPoms=false"
                        shellScript "mvn versions:update-child-modules -DgenerateBackupPoms=false"

                        dir('odf-bcb') {
                            shellScript "mvn versions:set -DnewVersion=${versionToRelease(TAG_NAME)} -DgenerateBackupPoms=false"
                        }

                        failWhen condition: mavenVersion().endsWith('-SNAPSHOT'), message: 'Cannot release snapshot artifact. Fix project version in pom.xml.'

                        failWhen condition: readMavenPom(file: 'odf-bcb\\pom.xml').with {
                            it.version != it.parent.version
                        }, message: '\'odf-bcb\' module version should be equal to parent version.'
                    }
                }

                stage('Build and deploy release artifacts') {
                    steps {
                        buildWithMaven configId: 'odf-maven-settings',
                                goals: ['clean', 'deploy'],
                                options: ['-Pci']
                    }
                }

                stage('Upload BCB and sources to AWS') {
                    steps {
                        withAWS(credentials: ' aa-materials-aws-keypair') {
                            s3Upload bucket: S3_BUCKET, path: "odf/dependencies/${mavenVersion()}/", file: "odf-bcb\\target\\odf-bcb-${mavenVersion()}.jar", acl: 'PublicRead'
                        }

                        buildWithMaven configId: 'odf-maven-settings', goals: ['clean']

                        zip zipFile: "odf-components-${mavenVersion()}-sources.zip"

                        withAWS(credentials: ' aa-materials-aws-keypair') {
                            s3Upload bucket: S3_BUCKET, path: "odf/src/${mavenVersion()}/", file: "odf-components-${mavenVersion()}-sources.zip", acl: 'PublicRead'
                        }
                    }
                }
            }
        }
    }
    post {
        success {
            slackMessage buildMessage: 'is successful', color: 'forestgreen', token: SLACK_AUTH_PSW, sonarLink: true, sonarDevelopersEdition: true
        }
        unstable {
            slackMessage buildMessage: 'is unstable', color: 'red', token: SLACK_AUTH_PSW
        }
        failure {
            slackMessage buildMessage: 'failed', color: 'red', token: SLACK_AUTH_PSW
        }
        aborted {
            slackMessage buildMessage: 'was aborted', color: 'red', token: SLACK_AUTH_PSW
        }
    }
}
