# Copyright 2022 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: 14400s # 2hr
substitutions:
  _PROJECT_ID: ${PROJECT_ID}
  _DESTROY_STATE_BUCKET: "false"
  _DESTROY_VPC: "false"
tags:
  - infra-destroy-terraform
steps:
 #  Destroy configuration installed in GKE clusters through ACM and the MCI feature
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-destroy-ACM-config"
    entrypoint: bash
    args:
      - -c
      - |
        exec gcloud builds submit --config builds/infra-destroy-features-mesh-gateways.yaml --substitutions=_PROJECT_ID=${_PROJECT_ID}
   #  Destroy GKE clusters
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-destroy-gke"
    entrypoint: bash
    args:
      - -c
      - |
        exec gcloud builds submit --config builds/terraform/infra-destroy-gke.yaml --substitutions=_PROJECT_ID=${_PROJECT_ID}
  # Destroy VPC
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-destroy-vpc"
    entrypoint: bash
    args:
      - -c
      - |
        [[ "${_DESTROY_VPC}" == "false" ]] && exit 0
        exec gcloud builds submit --config builds/terraform/infra-destroy-vpc.yaml --substitutions=_PROJECT_ID=${_PROJECT_ID}
  # Destroy ACM Repo
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-destroy-acm-repo"
    entrypoint: bash
    args:
      - -c
      - |
        exec gcloud builds submit --config builds/terraform/infra-destroy-repos.yaml --substitutions=_PROJECT_ID=${_PROJECT_ID}
  # Disable APIs
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-disable-apis"
    entrypoint: bash
    args:
      - -c
      - |
        exec gcloud builds submit --config builds/terraform/infra-disable-apis.yaml --substitutions=_PROJECT_ID=${_PROJECT_ID}

  # Destroy GCS storage bucket for TF state, project files, vars.sh etc
  # This step deletes the GCS storage bucket in the project with the name of project ID.
  - name: "gcr.io/cloud-builders/gcloud"
    id: "infra-delete-gcs"
    entrypoint: bash
    args:
      - -c
      - |
        [[ "${_DESTROY_STATE_BUCKET}" == "false" ]] && exit 0
        exec gcloud builds submit --config builds/terraform/infra-destroy-gcs.yaml --substitutions=_PROJECT_ID=${_PROJECT_ID} 
