#!/usr/bin/env groovy

pipeline {
    agent any

    options {
        timeout(time: 2, unit: 'HOURS')
    }

    environment {
        REVISION = ''
        CUSTOM_SCM_INFO = ''
    }

    stages {
        stage('Build') {
            steps {
                script {
                    def commitId = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
                    def commitDate = sh(returnStdout: true, script: 'git --no-pager show -s --format=%cd --date=short HEAD').trim()

                    REVISION = "${env.BRANCH_NAME}-${commitDate}.${commitId}"
                }
                sh "chmod -R +x ."
                sh "./gradlew -Pversion='${REVISION}' testClasses"
            }
        }

        stage('Test') {
            steps {
                sh "./gradlew --no-build-cache -Pversion='${REVISION}' -Dtestlogger.theme=plain-parallel test"
            }

            post {
                always {
                    junit '**/build/test-results/test/TEST-*.xml'
                }
            }
        }

        stage('Package') {
            steps {
                sh "./gradlew -Pversion='${REVISION}' jar -x test"
            }
        }
    }

    post {
        always {
            script {
                def commit = sh(returnStdout: true, script: 'git rev-parse HEAD')
                def author = sh(returnStdout: true, script: "git --no-pager show -s --format='%an' ${commit}").trim()
                def commitLog = sh(returnStdout: true, script: 'git log -1 --pretty=%B').trim()

                CUSTOM_SCM_INFO = "Latest Commit (${author}):```${commitLog}```"
            }

            deleteDir()
        }

        success {

            office365ConnectorSend color: 'good',
                    message: "Build ${currentBuild.fullDisplayName} completed *successfully* (<${BUILD_URL}>).\n\n\n${CUSTOM_SCM_INFO}",
                    webhookUrl: "https://outlook.office.com/webhook/97618564-835e-438e-a2a7-a77b21331e1e@22877e52-e9fd-410d-91a3-817d8ab89d63/JenkinsCI/fa736de2175649a891c2957f00532027/87d23462-1d0c-4378-b4e0-05c7d5546a25"
        }

        failure {
            office365ConnectorSend color: 'danger',
                    message: "Build ${currentBuild.fullDisplayName} *failed* (<${BUILD_URL}>).\n\n\n${CUSTOM_SCM_INFO}",
                    webhookUrl: "https://outlook.office.com/webhook/97618564-835e-438e-a2a7-a77b21331e1e@22877e52-e9fd-410d-91a3-817d8ab89d63/JenkinsCI/fa736de2175649a891c2957f00532027/87d23462-1d0c-4378-b4e0-05c7d5546a25"
        }

        unstable {
            office365ConnectorSend color: 'warning',
                    message: "Build ${currentBuild.fullDisplayName} was *unstable* (<${env.BUILD_URL}>).\n\n\n${CUSTOM_SCM_INFO}",
                    webhookUrl: "https://outlook.office.com/webhook/97618564-835e-438e-a2a7-a77b21331e1e@22877e52-e9fd-410d-91a3-817d8ab89d63/JenkinsCI/fa736de2175649a891c2957f00532027/87d23462-1d0c-4378-b4e0-05c7d5546a25"
        }
    }
}