# kate: indent-width 2;

parameters:
  dockerimage: ''  # defaults for any parameters that aren't specified
  module: ''
  jobname: ''

jobs:
- job: ${{ parameters.jobname }}
  timeoutInMinutes: 240
  pool:
    vmImage: 'Ubuntu-16.04'

  variables:
    DOCKER_TAG: ${{ parameters.dockerimage }}
    TRAVIS_BRANCH: $(Build.SourceBranchName)
    TRAVIS_COMMIT: $(Build.SourceVersion)
    MY_MODULE: ${{ parameters.module }}

  steps:
  - checkout: self
    submodules: true

  - task: Docker@1
    displayName: Container registry login
    inputs:
      command: login
      containerregistrytype: Container Registry
      dockerRegistryEndpoint: dockerhub

  - script: |
      BASEIMAGE="${MY_MODULE}-testing_${DOCKER_TAG}:${TRAVIS_BRANCH/\//_}"
      IMAGE="dunecommunity/ci_${MY_MODULE}-testing_${DOCKER_TAG}:${TRAVIS_COMMIT}"
      # get image with fallback to master branch of the super repo
      docker pull dunecommunity/${BASEIMAGE} || export BASEIMAGE="${MY_MODULE}-testing_${DOCKER_TAG}:master" ; docker pull dunecommunity/${BASEIMAGE}
      echo "##vso[task.setvariable variable=docker.baseimage]$BASEIMAGE"
      echo "##vso[task.setvariable variable=docker.image]$IMAGE"
      ENV_FILE=${HOME}/env
      echo "##vso[task.setvariable variable=docker.env]${ENV_FILE}"
      mkdir $(Agent.HomeDirectory)/testresults && chmod -R 777 $(Agent.HomeDirectory)/testresults
      DOCKER_RUN="docker run -v $(Agent.HomeDirectory)/testresults:/home/dune-ci/testresults --env-file ${ENV_FILE} ${IMAGE}"
      echo "##vso[task.setvariable variable=docker.run]${DOCKER_RUN}"
    displayName: 'env setup'

  - script: |
      docker build --build-arg BASE=$(docker.baseimage) -t $(docker.image) -f .ci/shared/docker/ci_run/Dockerfile .
      docker inspect $(docker.image)
    displayName: 'build image'

  - script: |
      python3 ./.ci/shared/scripts/make_env_file.py
      $(docker.run) /home/dune-ci/src/${MY_MODULE}/.ci/shared/scripts/test_cpp.bash
    displayName: 'test cpp'
    env:
      CODECOV_TOKEN: $(codecov.token)

  - script: |
      python3 ./.ci/shared/scripts/make_env_file.py
      $(docker.run) /home/dune-ci/src/${MY_MODULE}/.ci/shared/scripts/test_python.bash
    displayName: 'test python'
    env:
      CODECOV_TOKEN: $(codecov.token)

  - script: |
      docker push $(docker.image)
    displayName: 'docker push'
    condition: failed()

  - task: PublishTestResults@2
    inputs:
      testResultsFormat: 'JUnit'
      testResultsFiles: '$(Agent.HomeDirectory)/testresults/*xml'
    condition: always()
