pipeline {
    agent any

    options {
        disableConcurrentBuilds()
        ansiColor('xterm')
    }

    environment {
        COMPOSER_PROCESS_TIMEOUT = 900

        BUILD_UUID = "${JOB_BASE_NAME.replaceAll(/[^a-z0-9]/, '')}_${UUID.randomUUID()}"
        GIT_SHA1 = "${GIT_COMMIT.substring(0,7)}"
    }

    stages {
        stage('Install deps') {
            steps {
                echo 'Installing deps...'
            }
        }
        stage('Build') {
            steps {
                echo 'Building...'
                sh '''
                    phing \
                        prepare
                '''
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
                sh '''
                    phing \
                        phpunit phpcs phpcpd phpmd
                '''
            }
        }
    }

    post {
        always {
            echo 'Post actions : Always'
        }
        success {
            echo 'Post actions : Success'

            step([$class: 'XUnitBuilder',
                thresholds: [
                    [$class: 'SkippedThreshold', failureThreshold: '20'],
                    [$class: 'FailedThreshold', failureThreshold: '0']],
                tools: [
                    [$class: 'PHPUnitJunitHudsonTestType', pattern: '**/build/logs/phpunit-php7.xml'],
                ]
            ])

            // PMD
            step([$class: 'hudson.plugins.pmd.PmdPublisher', pattern: '**/build/logs/phpmd.xml'])

            // PHPCPD
            step([$class: 'hudson.plugins.dry.DryPublisher', pattern: '**/build/logs/phpcpd.xml', normalThreshold: 25, highThreshold: 50])

            // Checkstyle report
            step([$class: 'CheckStylePublisher', pattern: 'build/logs/checkstyle.xml', unHealthy: '40', healthy: '90', canComputeNew: false, defaultEncoding: ''])

            // Artifacts
            archiveArtifacts allowEmptyArchive: true, artifacts: 'var/logs/*.log', caseSensitive: true, defaultExcludes: true, fingerprint: false, onlyIfSuccessful: false
        }
        unstable {
            echo 'Post actions : Unstable'

            // Mailer notification
            step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: '', sendToIndividuals: true])

            // Slack notification
            slackSend channel: '#jenkins', message: "${JOB_NAME} | ${GIT_AUTHOR_NAME} :: ${GIT_SHA1} (${GIT_BRANCH}) (<${BUILD_URL}|Open>)", teamDomain: 'allocine', tokenCredentialId: 'slack'
        }
        failure {
            echo 'Post actions : Failure'
        }
        changed {
            echo 'Post actions : Changed'
        }
        cleanup {
            echo 'Post actions : Clean up'

            sh '''
                phing cleanup
            '''
        }
    }
}
