pipeline {
    agent any

    stages {
        stage('prepare') {
            steps {
                checkout scm
            }
        }
        stage("build and test") {
            parallel {
                stage("CRAY") {
                    stages {
                        stage('build') {
                            steps {
                                run_batch("0:30:00", "cray", "build")
                            }
                        }
                        // TODO: dbcsr_tensor_unittest is broken
                        // stage('test') {
                        //     steps {
                        //         run_batch("1:00:00", "cray", "test")
                        //     }
                        // }
                    }
                }
                stage("GNU") {
                    stages {
                        stage('build') {
                            steps {
                                run_batch("0:15:00", "gnu", "build")
                            }
                        }
                        stage('test') {
                            steps {
                                run_batch("1:00:00", "gnu", "test")
                            }
                        }
                    }
                }
                stage("Intel") {
                    stages {
                        stage('build') {
                            steps {
                                run_batch("0:30:00", "intel", "build")
                            }
                        }
                        stage('test') {
                            steps {
                                run_batch("1:00:00", "intel", "test")
                            }
                        }
                    }
                }
            }
        }
    }
}

def run_batch(timelimit, environment, task) {
    def (account, basename) = env.JOB_NAME.split('/')
    def sbatch_script = ".ci/daint.cscs.ch/${environment}.${task}.sh"
    def sbatch_out = "sbatch.${env.BUILD_TAG}.${environment}.${task}.out"

    // avoid using the shell for variable expansion to
    // get the final command displayed in Jenkins
    try {
        sh """
        sbatch --wait \
            --time="${timelimit}" \
            --account="${account}" \
            --job-name="${basename}.${environment}.${task}" \
            --output="${sbatch_out}" \
            ${sbatch_script}
        """
    }
    finally {
        echo readFile("${sbatch_out}")
    }
}

// vim: set filetype=groovy ts=4 sw=4 tw=0 :
