timeout: 5400s

steps:
# Deploy given tools to given locations. Expect 2 vars substitutions, examples:
# 1. $_REGIONS="us;us-east1;us-east2"
# 2. $_TOOLS="gve_vm_image_import;gce_vm_image_export"
# The script will pull the built docker images from gcr.io (container registry),
# and then push to artifacts registry (e.g. us-east1-docker.pkg.dev/compute-image-import/wrappers/gce_vm_image_import)
# with 3 tags: the workflow execution ID, the commit SHA, and the "release".
# 1. The workflow execution ID is used to track which workflow produced the image.
# It's specifically useful when the original workflow was failed and we resumed it.
# 2. The commit SHA is used to track which version of source code produced the image.
# 3. The "release" tag marks it as the current effective image.
- name: 'google/cloud-sdk:alpine'
  args:
  - 'bash'
  - '-c'
  - |
    REGIONS_ARR=$(echo "$_REGIONS" | tr ";" "\n")
    TOOLS_ARR=$(echo "$_TOOLS" | tr ";" "\n")
    GCP_PROJECTS_ARR=($_IMAGE_PROJECT)

    exit_on_error() {
      ERR=$$1
      if [[ $$ERR != 0 ]]; then
      echo "Deploy failed with exit code $$ERR. Please check the error message, debug and rerun."
      exit "$$ERR"
      fi
    }

    for _PROJECT in ${GCP_PROJECTS_ARR[@]}
    do
      for _REGION in $$REGIONS_ARR
      do
        for _TOOL in $$TOOLS_ARR
        do
          echo "--> Deploying... $$_TOOL -> $$_REGION"

          # Copy the new "release" from gcr.io and tag.
          gcloud container images add-tag gcr.io/$$_PROJECT/$$_TOOL:release $$_REGION-docker.pkg.dev/$$_PROJECT/wrappers/$$_TOOL:release -q
          exit_on_error $$?
          gcloud container images add-tag $$_REGION-docker.pkg.dev/$$_PROJECT/wrappers/$$_TOOL:release $$_REGION-docker.pkg.dev/$$_PROJECT/wrappers/$$_TOOL:$_WORKFLOW_EXECUTION_ID -q
          exit_on_error $$?
          gcloud container images add-tag $$_REGION-docker.pkg.dev/$$_PROJECT/wrappers/$$_TOOL:release $$_REGION-docker.pkg.dev/$$_PROJECT/wrappers/$$_TOOL:$COMMIT_SHA -q
          exit_on_error $$?
        done
        echo "----> Deployed all tools for $$_REGION"
      done
    done
