def createWorkflow() {

    properties([
        parameters([
            choice(
                choices: "2.3.48\n2.2.175\n2.1.84",
                description: 'Select a platform package reference.',
                name: 'platformPackageReference')
            ]),
        pipelineTriggers([])
    ])

    // Set some variables.
    def repoName = sh(returnStdout: true, script: 'git config remote.origin.url').trim().replaceAll('https://github.com/', '').replaceAll('-reference\\.git', '')
    def branchName = "${env.BRANCH_NAME}"
    def repoUrl = sh(returnStdout: true, script: 'git config remote.origin.url').trim().replaceAll('\\.git', '')
    def buildLink = "<${env.BUILD_URL}consoleFull|build #${env.BUILD_NUMBER}> for <${repoUrl}|${repoName}> on ${branchName}"
    def buildName = "${repoName}-${branchName}-${env.BUILD_NUMBER}".replaceAll('/', '-')


    withEnv(["COMPOSE_PROJECT_NAME=${buildName}","WORKSPACE=${env.WORKSPACE}","PATH+toolkit=${env.WORKSPACE}/vendor/ec-europa/toolkit/bin"]) {

        stage('Init') {
            setBuildStatus("Build started.", "PENDING");
            slackSend color: "good", message: "Subsite ${buildLink} started."
            sh 'cp vendor/ec-europa/toolkit/includes/phing/props/docker.props build.develop.props'
            shellExecute('jenkins', 'phing', "docker-compose-up -D'docker.project.id'='${env.COMPOSE_PROJECT_NAME}'")
         }

        try {
            stage('Phpcs') {
                shellExecute('docker', 'phing', 'test-run-phpcs')
            }
            stage('Build') {
                shellExecute('docker', 'phing', 'build-platform build-subsite-dev')
            }
            stage('Clone') {
                withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'ASDA', usernameVariable: 'ASDA_USER', passwordVariable: 'ASDA_PASS']]) {
                    shellExecute('docker', 'phing', "install-clone -Ddrupal.db.name=${env.COMPOSE_PROJECT_NAME} -Ddb.dl.username=$ASDA_USER -Ddb.dl.password=$ASDA_PASS")
                }
            }
            stage('Behat') {
                timeout(time: 2, unit: 'HOURS') {
                    shellExecute('docker', 'phing', 'test-run-behat')
                }
            }
        } catch(err) {
            setBuildStatus("Build failed.", "FAILURE");
            slackSend color: "danger", message: "Subsite build ${buildLink} failed."
            throw(err)
        } finally {
            shellExecute('jenkins', 'phing', "docker-compose-stop -D'docker.project.id'='${env.COMPOSE_PROJECT_NAME}'")
            shellExecute('jenkins', 'phing', "docker-compose-down -D'docker.project.id'='${env.COMPOSE_PROJECT_NAME}'")
            slackSend color: "good", message: "Subsite build ${buildLink} ended succesfully."
        }
    }
}

void setBuildStatus(String message, String state) {
    step([
        $class: "GitHubCommitStatusSetter",
        contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "${env.BUILD_CONTEXT}"],
        errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
        statusResultSource: [$class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]]]
    ]);
}

def shellExecute(String environment, String executable, String command) {

    switch("${environment}") {
        case "jenkins":
            prefix = ""
            break
        case "docker":
            prefix = "./docker-${env.COMPOSE_PROJECT_NAME} exec -T --user web web ./toolkit/"
            break
    }

    switch("${executable}") {
        case "phing":
            color = "-logger phing.listener.AnsiColorLogger"
            break
        case "composer":
            color = "--ansi"
            break
        default:
            color = ""
            break
    }

    sh "${prefix}${executable} ${command} ${color}"
}

return this;
