node('docker') {
  stage('Checkout repo') {
    checkout(
      [
        $class: 'GitSCM',
        branches: scm.branches,
        doGenerateSubmoduleConfigurations: scm.doGenerateSubmoduleConfigurations,
        extensions: scm.extensions,
        userRemoteConfigs: scm.userRemoteConfigs,
        extensions: [[
          $class: 'RelativeTargetDirectory',
          relativeTargetDir: 'doseme-algorithms'
        ]] + [[$class: 'CleanCheckout']]
      ]
    )
  }

  stage('Pull perlbase image') {
    def perlbase_image = docker.image('doseme/perlbase:latest')
    perlbase_image.pull()
  }

  def algorithms_image

  stage('Setup algorithms image') {
    algorithms_image = docker.build("doseme-algorithms", "-f doseme-algorithms/Dockerfile doseme-algorithms")
  }

  stage('Test algorithms image') {
    try {
      algorithms_image.inside("-e HOME=/home/jenkins") {
        sh '''
          /bin/bash -c "
              eval '\$(perl -I\$HOME/perl5/lib/perl5 -Mlocal::lib)' &&
              cpanm --mirror=https://darkpan.doseme.com.au --mirror=https://cpan.metacpan.org/ --mirror-only -v --installdeps ./doseme-algorithms &&
              cd doseme-algorithms &&
              dzil build --no-tgz &&
              cd DoseMe-Algorithms-* &&
              (AUTHOR_TESTING=1 prove -blv -j8 --formatter=TAP::Formatter::JUnit > ../../junit.xml || true) &&
              (perl -Ilib t/test-coverage.t > ../../test-coverage-report.txt || true) &&
              cd .. &&
              dzil clean
          "
        '''
      }
    } finally {
      junit 'junit.xml'
      archiveArtifacts artifacts: 'test-coverage-report.txt'
    }
  }
}
