# Required pipeline variables:
# - BUILD_POOL - Azure DevOps build pool to use
# - CONTAINER_IMAGE - Dev container image URL to use. Should have Azure CLI, Packer and Ansible.
# - AZURE_TENANT_ID - tenant ID
# - AZURE_CLIENT_ID - Service principal ID
# - AZURE_CLIENT_SECRET - Service principal secret
# - AZURE_SUBSCRIPTION_ID - Subscription ID used by the pipeline
# - KUBERNETES_VERSION - version of Kubernetes to build the image with, e.g. `1.16.2`
# - OS - target of build e.g. `Ubuntu/Windows`
# - OS_VERSION - target of build e.g. `18.04/2004/2019`

jobs:
- job: build_vhd
  container: $[ variables['CONTAINER_IMAGE'] ]
  timeoutInMinutes: 120
  strategy:
    maxParallel: 0
  pool:
    name: $(BUILD_POOL)
  steps:
  - template: k8s-config.yaml
  - script: |
      set -o pipefail
      make deps-azure
      os=$(echo "${OS}" | tr '[:upper:]' '[:lower:]')
      version=$(echo "${OS_VERSION}" | tr '[:upper:]' '[:lower:]' | tr -d .)
      export RESOURCE_GROUP_NAME="cluster-api-images"

      # timestamp is in RFC-3339 format to match kubetest
      export TIMESTAMP="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
      export JOB_NAME="${JOB_NAME:-"image-builder-vhd"}"
      export TAGS="creationTimestamp=${TIMESTAMP} jobName=${JOB_NAME}"
      printf "${TAGS}" | tee packer/azure/tags.out
      make build-azure-vhd-$os-$version | tee packer/azure/packer.out
    displayName: Building VHD
    workingDirectory: '$(system.defaultWorkingDirectory)/images/capi'
    env:
      AZURE_CLIENT_SECRET: $(AZURE_CLIENT_SECRET)
  - template: generate-sas.yaml
  - template: vhd-publishing-info.yaml
  - task: PublishPipelineArtifact@1
    inputs:
      artifact: 'publishing-info'
      path: '$(system.defaultWorkingDirectory)/images/capi/packer/azure/vhd-publishing-info.json'
    condition: eq(variables.CLEANUP, 'False')
  - template: delete-storage-account.yaml
  - script: |
      chown -R $USER:$USER .
    displayName: cleanup - chown all files in work directory
    condition: always()