steps:

- id: 'Build Container Image'
  name: 'gcr.io/cloud-builders/docker:latest'
  dir: '${_SAMPLE_DIR}'
  args: ['build', '-t', '${_IMAGE_NAME}', '.']

- id: 'Push Container Image'
  name: 'gcr.io/cloud-builders/docker:latest'
  args: ['push', '${_IMAGE_NAME}']

- id: 'Deploy to Cloud Run'
  name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:$_CLOUDSDK_VERSION'
  entrypoint: /bin/bash
  args:
  - -c
  - |
    gcloud run deploy ${_SERVICE}-$BUILD_ID \
     --image ${_IMAGE_NAME} \
     --cluster ${_CLUSTER} \
     --cluster-location ${_CLUSTER_LOCATION} \
     --platform gke

- id: 'Get Cloud Run URL'
  name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:$_CLOUDSDK_VERSION'
  entrypoint: '/bin/bash'
  args:
  - '-c'
  - |
    set -e
    source /workspace/testing/cloudbuild-templates/common.sh
    echo $(get_url ${BUILD_ID}) > _service_url
    echo "Cloud Run URL for ${_SERVICE}-$BUILD_ID is $(cat _service_url)"

- id: 'Get Cloud Run External IP'
  name: 'gcr.io/cloud-builders/kubectl'
  entrypoint: '/bin/bash'
  args:
  - '-c'
  - |
    get_ip() {
        gcloud container clusters get-credentials ${_CLUSTER} --zone ${_CLUSTER_LOCATION} --project ${PROJECT_ID} \
        && kubectl get svc istio-ingress --namespace gke-system \
          --output 'jsonpath={.status.loadBalancer.ingress[0].ip}'
    }
    echo $(get_ip) > _service_ip

- id: 'Integration Tests'
  # TODO: Update the following image name, entrypoint, and args to fit your testing needs
  name: 'gcr.io/cloud-builders/curl'
  entrypoint: '/bin/sh'
  dir: '${_SAMPLE_DIR}'
  args:
  - '-c'
  - |
    echo "Add integration tests!"

- id: 'Teardown'
  name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:$_CLOUDSDK_VERSION'
  entrypoint: '/bin/bash'
  args:
  - '-c'
  - |
    set -x
    gcloud --quiet container images delete ${_IMAGE_NAME}
    gcloud --quiet run services delete ${_SERVICE}-$BUILD_ID --platform gke
    set +x
    echo "View build details in the console: https://console.cloud.google.com/cloud-build/builds/${BUILD_ID}"

# Uncomment if skipping teardown to associate build with container image.
# images:
# - '${_IMAGE_NAME}'

options:
  dynamicSubstitutions: true

# TODO: Update these User-defined substitutions
substitutions:
  _SERVICE: SERVICE_NAME
  _SAMPLE_DIR: SAMPLE_DIRECTORY
  _CLUSTER: CLUSTER_NAME
  _CLUSTER_LOCATION: _CLUSTER_LOCATION
  _CLOUDSDK_VERSION: latest
  _AR_REPO_NAME: samples
  _AR_REGION_NAME: us-central1
  _IMAGE_NAME: ${_AR_REPO_REGION}-docker.pkg.dev/${PROJECT_ID}/${_AR_REPO_NAME}/${_SERVICE}:${SHORT_SHA}   # Tag docker image with git commit sha
