pipeline {
    agent {
        docker {
            image 'dillonngo/docker-based-image:poc'
            args "--group-add 992 -v /var/run/docker.sock:/var/run/docker.sock"
        }
    }
    environment {
        HOME = '.'
    }
    stages {
        stage('Download source code from Git') {
             steps {
                script{
                    switch(GIT_BRANCH) {
                        case "vapor/production":
                            git(
                                url: 'https://gitlab.com/CIEFWorldwideSdnBhd/vapor-laravel-explore.git',
                                credentialsId: 'gitlab-jenkins-localhost',
                                branch: 'vapor/production'
                            )
                        break
                        case "vapor/staging":
                            git(
                                url: 'https://gitlab.com/CIEFWorldwideSdnBhd/vapor-laravel-explore.git',
                                credentialsId: 'gitlab-jenkins-localhost',
                                branch: 'vapor/staging'
                            )
                        break
                        case "origin/test":
                            git(
                                url: 'https://gitlab.com/CIEFWorldwideSdnBhd/vapor-laravel-explore.git',
                                credentialsId: 'gitlab-jenkins-localhost',
                                branch: 'test'
                            )
                        break
                    }
                }
            }
        }

        stage('Install') {
            steps {
                sh 'composer update'
            }
        }

        stage('Tests') {
            steps {
                sh 'vendor/bin/phpunit tests/Unit'
            }
        }

        stage('Deploy') {
            steps {
                script{
                    String gitCommitMessage = getCommitMessage()
                    println("GIT CommitMessage: " + gitCommitMessage)
                    switch(GIT_BRANCH) {
                        case "vapor/production":
                            sh "vendor/bin/vapor deploy production --message='${gitCommitMessage}'"
                        break
                        case "vapor/staging":
                            sh "vendor/bin/vapor deploy staging --message='${gitCommitMessage}'"
                        break
                        case "origin/test":
                            sh "vendor/bin/vapor deploy development --message='${gitCommitMessage}'"
                        break
                    }
                }
            }
        }

    }
}

@NonCPS
String getCommitMessage(){
    commitMessage = " "
    for ( changeLogSet in currentBuild.changeSets){
        for (entry in changeLogSet.getItems()){
            commitMessage = entry.msg
        }
    }
    return commitMessage
}
