pipeline {
    agent any

    environment {
        PROJECT_NAME = 'colibri-auction'
        WWW_ROOTFOLDER = '/var/www/colibriauction'
    }

    parameters {
        booleanParam(name: 'IMMEDIATELY', defaultValue: false, description: 'if it is true, then the new application immediately appears on PROD server')
    }

    stages {

        stage('Clone repository') {
            steps {
                git url: "ssh://git-codecommit.ap-southeast-1.amazonaws.com/v1/repos/${PROJECT_NAME}", branch: 'master', credentialsId: 'ciagent-git'
            }
        }

        stage('Pull source code and deploy on QA') {
            agent {
                label 'ausante-qa'
            }
            steps {
                dir ("${WWW_ROOTFOLDER}") {
                    sh 'pwd'
                    sh 'git pull origin master'
                    sh 'composer install'
                    sh 'php artisan migrate --force'
                    sh 'php artisan config:clear'
                    sh 'php artisan view:clear'

                    sh 'sudo supervisorctl stop all'
                    sh 'sudo supervisorctl reread'
                    sh 'sudo supervisorctl update'
                    sh 'sudo supervisorctl start all'

                    sh 'sudo pm2 start nodeJS/ecosystem.config.js'
                }
            }
        }

        stage('Pull source code and deploy on Prod') {
            agent {
                label 'colibriauction-live'
            }
            when {
                expression {
                    return params.IMMEDIATELY
                }
            }
            steps {
                dir ("${WWW_ROOTFOLDER}") {
                    sh 'pwd'
                    sh 'git pull origin master'
                    sh 'composer install'
                    sh 'php artisan migrate --force'
                    sh 'php artisan config:clear'
                    sh 'php artisan view:clear'

                    sh 'sudo supervisorctl stop all'
                    sh 'sudo supervisorctl reread'
                    sh 'sudo supervisorctl update'
                    sh 'sudo supervisorctl start all'

                    sh 'sudo pm2 start nodeJS/ecosystem.config.js'
                }
            }
        }
    }
}
