# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

timeout: 10800s
substitutions:
  _ACTION: apply
  _NAME: broker
tags:
  - kube-app-launcher-base
  - kube-app-launcher-setup
steps:
  ###
  # Cleanup any existing sub-jobs to prevent overlapping executions.
  ###
  - name: "gcr.io/cloud-builders/gcloud"
    id: cleanup-sub-jobs
    entrypoint: bash
    args:
      - -c
      - |
        gcloud -q builds list --ongoing --filter='tags[]~kube-app-launcher-infra' --format='value(id)' | \
          xargs --no-run-if-empty gcloud -q builds cancel >/dev/null
  ###
  # Create GCS bucket to store terraform state
  ###
  - name: "gcr.io/cloud-builders/gsutil"
    id: "create-tf-state-bucket"
    entrypoint: "/bin/bash"
    args:
      - "-xe"
      - "-c"
      - |
        gsutil mb gs://${PROJECT_ID}-${_NAME}-tf-state || true
    waitFor: ["-"]
  ###
  # Builds the image used to run the deployment
  ###
  - name: 'gcr.io/cloud-builders/docker'
    id: installer-image-pull
    entrypoint: 'bash'
    args: ["-c", "if [[ '${_USE_CACHE}' == 'true' ]]; then (docker pull gcr.io/${PROJECT_ID}/${_NAME}-installer:latest || exit 0); fi"]
    waitFor: ["-"]
  - name: 'gcr.io/cloud-builders/docker'
    id: build-installer-image
    args: [
              'build',
              '-t', 'gcr.io/${PROJECT_ID}/${_NAME}-installer:latest',
              '.'
          ]
    waitFor:
      - installer-image-pull
  - name: 'gcr.io/cloud-builders/docker'
    id: push-installer-image
    args: [
              'push',
              'gcr.io/${PROJECT_ID}/${_NAME}-installer:latest',
          ]
    waitFor:
      - build-installer-image
  ###
  # base infrasturcture
  ###
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-base-terraform"
    args:
      - "builds"
      - "submit"
      - "infra"
      - "--config"
      - "infra/cloudbuild.yaml"
      - "--substitutions"
      - "_NAME=${_NAME},_ACTION=${_ACTION}"
