# Copyright 2024 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
#
#     https://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.

name: 'tf-apply'
on:
  push:
    branches:
      - 'development'
      - 'production'
      - 'nonproduction'

env:
  PROJECT_ID: ${{ secrets.PROJECT_ID }}
  TF_BACKEND: ${{ secrets.TF_BACKEND }}
  TF_VAR_gh_token: ${{ secrets.TF_VAR_gh_token }}
  TF_VAR_github_app_infra_token: ${{ secrets.TF_VAR_github_app_infra_token }}
  TF_IN_AUTOMATION: "true"

jobs:
  run:
    runs-on: 'ubuntu-latest'
    permissions:
      contents: 'read'
      id-token: 'write'

    steps:
      - uses: 'actions/checkout@v3'

      - id: 'auth'
        uses: 'google-github-actions/auth@v1'
        with:
          token_format: 'access_token'
          workload_identity_provider: ${{ secrets.WIF_PROVIDER_NAME }}
          service_account: ${{ secrets.SERVICE_ACCOUNT_EMAIL }}

      - uses: 'google-github-actions/setup-gcloud@v1'
        with:
          install_components: "beta,terraform-tools"

      - uses: 'hashicorp/setup-terraform@v2'
        with:
          terraform_version: '1.5.7'

      - id: setup
        shell: bash
        run: |
          echo "Adding bucket information to backends"
          for i in `find . -name 'backend.tf'`
          do
            sed -i'' -e "s/UPDATE_ME/${TF_BACKEND}/" $i
            sed -i'' -e "s/UPDATE_PROJECTS_BACKEND/${TF_BACKEND}/" $i
          done

      - id: init
        run: |
          echo "terraform init"
          ${GITHUB_WORKSPACE}/tf-wrapper.sh init "${GITHUB_REF_NAME}"

      - id: plan
        run: |
          echo "terraform plan"
          ${GITHUB_WORKSPACE}/tf-wrapper.sh plan "${GITHUB_REF_NAME}" "${GITHUB_WORKSPACE}/policy-library" "${PROJECT_ID}" "FILESYSTEM" "GITHUB"

      - id: validate
        run: |
          echo "validate"
          ${GITHUB_WORKSPACE}/tf-wrapper.sh validate "${GITHUB_REF_NAME}" "${GITHUB_WORKSPACE}/policy-library" "${PROJECT_ID}" "FILESYSTEM" "GITHUB"

      - id: apply
        run: |
          echo "terraform apply"
          ${GITHUB_WORKSPACE}/tf-wrapper.sh apply "${GITHUB_REF_NAME}" "${GITHUB_WORKSPACE}/policy-library" "${PROJECT_ID}" "FILESYSTEM" "GITHUB"
