#!groovy

import org.csanchez.jenkins.plugins.kubernetes.pipeline.PodTemplateAction

def phpVersion = "7.1"
def mysqlVersion = "5.7"
def launchUnitTests = "yes"
def launchIntegrationTests = "yes"
def launchBehatTests = "yes"

class Globals {
    static pimVersion = "2.0"
    static extensionBranch = "dev-master"
}

stage("Checkout") {
    milestone 1
    if (env.BRANCH_NAME =~ /^PR-/) {
        userInput = input(message: 'Launch tests?', parameters: [
            choice(choices: 'yes\nno', description: 'Run unit tests', name: 'launchUnitTests'),
            choice(choices: 'yes\nno', description: 'Run integration tests', name: 'launchIntegrationTests'),
        ])

        launchUnitTests = userInput['launchUnitTests']
        launchIntegrationTests = userInput['launchIntegrationTests']
    }
    milestone 2

    podPHP(phpVersion, {
        
        checkout scm
        stash "excel_init"

        checkout([$class: 'GitSCM',
             branches: [[name: "${Globals.pimVersion}"]],
             userRemoteConfigs: [[credentialsId: 'github-credentials', url: 'https://github.com/akeneo/pim-community-standard.git']]
        ])
        stash "pim_community"

        checkout([$class: 'GitSCM',
            branches: [[name: "${Globals.pimVersion}"]],
            userRemoteConfigs: [[credentialsId: 'github-credentials', url: 'https://github.com/akeneo/pim-enterprise-standard.git']]
        ])
        sh "chmod -R 777 ${env.WORKSPACE}"
        stash "pim_enterprise"
    })
}

if (launchUnitTests.equals("yes")) {
    stage("Unit tests") {
        def tasks = [:]

        tasks["phpspec-7.1"] = {runPhpSpecTest(phpVersion)}
        tasks["php-cs-fixer-7.1"] = {runPhpCsFixerTest(phpVersion)}

        parallel tasks
    }
}

if (launchIntegrationTests.equals("yes")) {
    stage("Integration tests") {
        def tasks = [:]

        tasks["phpunit-7.1-ce"] = {runIntegrationTest(phpVersion)}
        tasks["phpunit-7.1-ee"] = {runIntegrationTestEE(phpVersion)}

        parallel tasks
    }
}

def runPhpSpecTest(version) {
    podPHP(version, { 
        
        try {
            unstash "excel_init"

            sh "composer install --optimize-autoloader --no-interaction --no-progress --prefer-dist"
            sh "mkdir -p app/build/logs/"
            sh "./bin/phpspec run --no-interaction --format=junit > app/build/logs/phpspec.xml"
        } finally {
            sh "sed -i \"s/testcase name=\\\"/testcase name=\\\"[php-${version}] /\" app/build/logs/*.xml"
            junit "app/build/logs/*.xml"
            
        }
    })
}

def runPhpCsFixerTest(version) {
    podPHP(version, {
        
        try {
            unstash "excel_init"

            sh "composer install --optimize-autoloader --no-interaction --no-progress --prefer-dist"
            sh "mkdir -p app/build/logs/"
            sh "./bin/php-cs-fixer fix --diff --format=junit --config=.php_cs.php > app/build/logs/phpcs.xml"
        } finally {
            sh "sed -i \"s/testcase name=\\\"/testcase name=\\\"[php-${version}] /\" app/build/logs/*.xml"
            junit "app/build/logs/*.xml"
        }
    })
}

def runIntegrationTest(version) {
    podIntegration(version, {
        unstash "pim_community"

        sh "composer require --no-update phpunit/phpunit akeneo/excel-init-bundle:${Globals.extensionBranch}"
        sh "composer update --optimize-autoloader --no-interaction --no-progress --prefer-dist"
        sh "chmod -R 777 ${env.WORKSPACE}"
        sh "bin/console assets:install"
        sh "bin/console pim:installer:dump-require-paths"

        dir("vendor/akeneo/excel-init-bundle") {
            
            unstash "excel_init"
        }
        sh "composer dump-autoload -o"

        sh "cp app/config/parameters.yml.dist app/config/parameters_test.yml"
        sh "sed -i 's/database_host:.*/database_host: 127.0.0.1/' app/config/parameters_test.yml"
        sh "echo '' >> app/config/parameters_test.yml"
        sh "echo '    pim_installer.fixture_loader.job_loader.config_file: PimExcelInitBundle/Resources/config/fixtures_jobs.yml' >> app/config/parameters_test.yml"
        sh "echo '    installer_data: PimExcelInitBundle:minimal' >> app/config/parameters_test.yml"
        sh "sed -i \"s#index_hosts: .*#index_hosts: '127.0.0.1:9200'#g\" app/config/parameters_test.yml"
        sh "sed -i 's#// your app bundles should be registered here#\\0\\nnew Pim\\\\Bundle\\\\ExcelInitBundle\\\\PimExcelInitBundle(),#' app/AppKernel.php"
        
        sh "sleep 10"
        
        sh "./bin/console --env=test pim:install --force"
    })
}

def runIntegrationTestEE(version) {
    podIntegration(version, {
        unstash "pim_enterprise"

        sh "composer require --no-update phpunit/phpunit akeneo/excel-init-bundle:${Globals.extensionBranch}"
        sh "composer update --optimize-autoloader --no-interaction --no-progress --prefer-dist"
        sh "chmod -R 777 ${env.WORKSPACE}"
        sh "bin/console assets:install"
        sh "bin/console pim:installer:dump-require-paths"

        dir("vendor/akeneo/excel-init-bundle") {
            unstash "excel_init"
        }
        sh "composer dump-autoload -o"

        sh "cp app/config/parameters.yml.dist app/config/parameters_test.yml"
        sh "sed -i 's/database_host:.*/database_host: 127.0.0.1/' app/config/parameters_test.yml"
        sh "echo '' >> app/config/parameters_test.yml"
        sh "echo '    pim_installer.fixture_loader.job_loader.config_file: PimExcelInitBundle/Resources/config/fixtures_jobs_ee.yml' >> app/config/parameters_test.yml"
        sh "echo '    installer_data: PimExcelInitBundle:minimal_EE' >> app/config/parameters_test.yml"
        sh "sed -i \"s#index_hosts: .*#index_hosts: '127.0.0.1:9200'#g\" app/config/parameters_test.yml"
        sh "sed -i 's#// your app bundles should be registered here#\\0\\nnew Pim\\\\Bundle\\\\ExcelInitBundle\\\\PimExcelInitBundle(),#' app/AppKernel.php"
        
        sh "sleep 10"
        sh "./bin/console --env=test pim:install --force"
    })
}

def podPHP(phpVersion, body) {
    def podName = "ExcelInitBundle-" + UUID.randomUUID().toString()
    withCredentials([string(credentialsId: 'composer-token', variable: 'token')]) {
        podTemplate(label: podName, containers: [
            containerTemplate(name: "php", ttyEnabled: true, command: 'cat', image: "akeneo/php:${phpVersion}", resourceRequestCpu: '100m', resourceRequestMemory: '1000Mi',
                envVars: [
                    envVar(key: "COMPOSER_HOME", value: "${env.WORKSPACE}/.composer"),
                    envVar(key: "COMPOSER_AUTH", value: "{\"github-oauth\":{\"github.com\": \"$token\"}}")
                ]        
            ),    
        ]) {  
            node(podName) {
                container("php") {
                    body()
                }
            }
        }
        }
}


def podIntegration(phpVersion, body) {
    def podName = "ExcelInitBundle-" + UUID.randomUUID().toString()
    withCredentials([string(credentialsId: 'composer-token', variable: 'token')]) {
        podTemplate(label: podName, containers: [
            containerTemplate(name: "elasticsearch", image: "elasticsearch:5.5", resourceRequestCpu: '100m', resourceRequestMemory: '200Mi',
                envVars: [
                    envVar(key: "ES_JAVA_OPTS", value: "-Xms256m -Xmx256m"),
                    envVar(key: "FORCE", value: "true"),
                    ]        
            ),
            containerTemplate(name: "mysql", image: "mysql:5.7", resourceRequestCpu: '100m', resourceRequestMemory: '200Mi', 
                envVars: [
                    envVar(key: "MYSQL_ROOT_PASSWORD", value: "root"),
                    envVar(key: "MYSQL_USER", value: "akeneo_pim"),
                    envVar(key: "MYSQL_PASSWORD", value: "akeneo_pim"),
                    envVar(key: "MYSQL_DATABASE", value: "akeneo_pim"),
                ], volumes: [

                    emptyDirVolume(memory: false, mountPath: "/var/lib/mysql"),
                    emptyDirVolume(memory: false, mountPath: "/tmp")
                ]
            
            ),
            containerTemplate(name: "php", ttyEnabled: true, command: 'cat', image: "akeneo/php:${phpVersion}", resourceRequestCpu: '100m', resourceRequestMemory: '1000Mi',
                envVars: [
                    envVar(key: "COMPOSER_HOME", value: "${env.WORKSPACE}/.composer"),
                    envVar(key: "COMPOSER_AUTH", value: "{\"github-oauth\":{\"github.com\": \"$token\"}}")
                ]        
            ),    
        ]) { 
            node(podName) {
                container("php") {
                    sh "chmod -R 777 /tmp"
                    body()
                }
            }
        }
    }
}


@NonCPS
def clearTemplateNames() {
    // see https://issues.jenkins-ci.org/browse/JENKINS-42184
    def action = currentBuild.rawBuild.getAction(PodTemplateAction.class);
    if(action) { action.names.clear() }
}
