@Library('test-shared-library') _

def DEFAULT_NODE_LABEL = 'h2o-3'
final int HEALTH_CHECK_RETRIES = 5

def defineTestStages = null
def pipelineContext = null
def result = 'FAILURE'
def scmEnv = null

try {
  ansiColor('xterm') {
    timestamps {

      boolean healthCheckPassed = false
      int attempt = 0
      stage('Checkout and Build') {
        while (!healthCheckPassed) {
          attempt += 1
          if (attempt > HEALTH_CHECK_RETRIES) {
            error "Too many attempts to pass initial health check"
          }
          String nodeLabel = DEFAULT_NODE_LABEL
          if (pipelineContext != null) {
            nodeLabel = "h2o-3"
          }
          echo "######### NodeLabel: ${nodeLabel} #########"
          node(nodeLabel) {
            dir('h2o-3') {
              // clear the folder
              deleteDir()
              // checkout H2O-3
              retryWithTimeout(180, 3) {
                echo "###### Checkout H2O-3 ######"
                scmEnv = checkout scm
              }
            }

            if (pipelineContext == null) {
              def initPipelineContext = load('h2o-3/scripts/jenkins/groovy/initPipelineContext.groovy')
              pipelineContext = initPipelineContext(scmEnv, 'MODE_SINGLE_TEST', true)
              pipelineContext.getBuildConfig().setJobProperties(this, parameters([
                      choice(choices: ['Python', 'R'].join("\n"), description: 'Component which will be tested.', name: 'testComponent'),
                      choice(choices: ['3.6', '3.7', '3.8', '3.9'].join("\n"), description: 'Component which will be tested.', name: 'singleTestPyVersion'),
                      choice(choices: ['3.3.3', '3.4.1'].join("\n"), description: 'Component which will be tested.', name: 'singleTestRVersion'),
                      string(defaultValue: null, description: 'Path to test which will be executed. For example <code>testdir_algos/gbm/pyunit_bernoulli_gbm.py</code> - <strong>no h2o-py/test/</strong> in the beginning.', name: 'testPath'),
                      string(defaultValue: '10g', description: 'Maximum size, of the memory allocation pool.', name: 'singleTestXmx'),
                      string(defaultValue: '1', description: 'Number of H2O clouds to start.', name: 'singleTestNumClouds'),
                      string(defaultValue: '1', description: 'How many H2O java instances are in a cloud.  Clouds are symmetric.', name: 'singleTestNumNodes'),
                      string(defaultValue: '1', description: 'How many times the test should be executed.', name: 'singleTestNumRuns')
              ]))
              // Load the defineTestStages script
              defineTestStages = load('h2o-3/scripts/jenkins/groovy/defineTestStages.groovy')
            }
            healthCheckPassed = pipelineContext.getHealthChecker().checkHealth(this, env.NODE_NAME, pipelineContext.getBuildConfig().getDefaultImage(), pipelineContext.getBuildConfig().DOCKER_REGISTRY, pipelineContext.getBuildConfig())
            if (healthCheckPassed) {
              // Load build script and execute it
              def buildH2O3 = load('h2o-3/scripts/jenkins/groovy/buildH2O3.groovy')
              buildH2O3(pipelineContext)
            }
          }
        }
      }

      defineTestStages(pipelineContext)
      result = 'SUCCESS'
    }
  }
} finally {
  if (pipelineContext != null) {
//    pipelineContext.getEmailer().sendEmail(this, result, pipelineContext.getBuildSummary().getSummaryHTML(this))
    if (!pipelineContext.getHealthChecker().getHealthProblems().isEmpty()) {
      pipelineContext.getEmailer().sendEmail(this, 'WARNING', pipelineContext.getHealthChecker().toEmail(this, pipelineContext), ['michalr@h2o.ai'])
    }
  }
}
