nodeName = getNode()
node (nodeName) {
    // Clean workspace before doing anything
    deleteDir()

    MAGENTO_DIR='magento'
    DEPLOY_DIR='deploy'
    DATABASE_USER='root'
    DATABASE_PASS='k4m4l30n'

    branchInfo = getBranch()
    projectName = getCleanName()
    artifactName = getArtifactName()
    try {
        slackSend (channel: '#jenkins', color: '#FFFF00', message: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
        if (branchInfo.type != 'develop') {
              stage ('Confirm Deploy') {
                  confirmedServer = confirmServerToDeploy()
              }    
        }
        stage ('Clone') {
            checkout scm
            sh "git ls-files -i --exclude-standard | xargs -r git rm -f -r --cached --ignore-unmatch"
        }
        if (branchInfo.type == 'develop') {
            stage ('Artifact') {
                retry(3) {
                    sh "composer install --no-dev --prefer-dist --optimize-autoloader"
                    sh "bin/dep -f=${DEPLOY_DIR}/deploy.php build dev --artifactFilename=${artifactName} -vvv"
                }
            }
            stage ('Deploy DEV') {
                 sh "bin/dep -f=${DEPLOY_DIR}/deploy.php deploy dev --artifactFilename=${artifactName} -vvv"
                 sh "bin/dep -f=${DEPLOY_DIR}/deploy.php restart:all:caches dev -vvv"
            }
        }
        if (branchInfo.type != 'develop') {
            stage ('Install') {
                sh "composer install"
            }
            stage ('Tests') {
               parallel(
                    /*
                    static: {
                        sh "bin/grumphp run"
                    },*/
                    unit: {
                        sh "bin/phpunit -c ${MAGENTO_DIR}/dev/tests/unit/phpunit.xml"
                    }
                   /* ,
                    integration: {
                        sh "bin/mg2-builder tests-setup:install -Dproject.name=${projectName} -Ddatabase.admin.username=${DATABASE_USER} -Ddatabase.admin.password=${DATABASE_PASS} -Ddatabase.user=${DATABASE_USER} -Ddatabase.password=${DATABASE_PASS} -DskipDbUserCreation"
                        sh "bin/phpunit -c ${MAGENTO_DIR}/dev/tests/integration/phpunit.xml"
                    }*/
               )
            }
            if (confirmedServer) {
                  stage ('Artifact') {
                    sh "composer install --no-dev --prefer-dist --optimize-autoloader"
                    sh "bin/dep -f=${DEPLOY_DIR}/deploy.php build dev --artifactFilename=${artifactName} -vvv"
                    if (branchInfo.type == 'master') {
                        archiveArtifacts('**/*.tar.gz')
                    }
                  }
                if (confirmedServer in ['staging','both']) {
                    stage ('Deploy Staging') {
                          sh "bin/dep -f=${DEPLOY_DIR}/deploy.php deploy staging --artifactFilename=${artifactName} -vvv"
                          sh "bin/dep -f=${DEPLOY_DIR}/deploy.php restart:all:caches staging -vvv"
                    }
                }
                  if (confirmedServer in ['production','both']) {
                      stage ('Deploy PROD') {
                          sh "bin/dep -f=${DEPLOY_DIR}/deploy.php deploy prod --artifactFilename=${artifactName} -vvv"
                      }
                  }
             }
         }
        stage ('Clean Up') {
            deleteDir()
        }
        slackSend (channel: '#jenkins', color: '#00FF00', message: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
    } catch (err) {
        currentBuild.result = 'FAILED'
        slackSend (channel: '#jenkins', color: '#FF0000', message: " @here FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
        throw err
    }
}

def getArtifactName() {
    return UUID.randomUUID().toString()
}

def getCleanName() {
    def projectRealName = JOB_NAME.replace('/','_');
    projectRealName = projectRealName.replace('-','_');
    return projectRealName
}

def getNode() {
    branch = getBranch();
    node = '';
    //Use node slave to run Magento 2.3 in i4 Jenkins
    if (branch.type == 'develop') {
       node = 'magento_23';
    }
    return node
}


def getBranch() {
    def branch = [:]
    branchData = BRANCH_NAME.split('/')
    if (branchData.size() == 2) {
        branch['type'] = branchData[0]
        branch['version'] = branchData[1]
    } else {
        branch['type'] = BRANCH_NAME
        branch['version'] = BRANCH_NAME
    }
    return branch
}

def confirmServerToDeploy() {
    def server = false
    try {
        timeout(time:2, unit:'HOURS') {
            server = input(
                id: 'environmentInput', message: 'Deployment Settings', parameters: [
                choice(choices: "staging\nproduction\nboth", description: 'Target server to deploy', name: 'deployServer')
            ])
        }
    } catch (err) {
        echo "Timeout expired. Environment was not set by user"
    }
    return server
}