# Copyright 2023 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-pull-request'
on:
  pull_request:
    branches:
      - 'development'
      - 'production'
      - 'non-production'

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

jobs:
  run:
    runs-on: 'ubuntu-latest'
    permissions:
      contents: 'read'
      id-token: 'write'
      issues: 'write'
      pull-requests: '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.3'

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

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

      - uses: actions/github-script@v6
        if: github.event_name == 'pull_request'
        env:
          PLAN_VALIDATE_ALL: "\n${{ steps.plan-validate-all.outputs.stdout }}"
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            })
            const botComment = comments.find(comment => {
              return comment.user.type === 'Bot' && comment.body.includes('Terraform Initialization')
            })

            const output = `
            #### Terraform Plan Validate All 📖\`${{ steps.plan-validate-all.outcome }}\`

            <details><summary>Show Plan</summary>

            \`\`\`\n
            ${process.env.PLAN_VALIDATE_ALL}
            \`\`\`

            </details>`;

            if (botComment) {
              github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: output
              })
            } else {
              github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body: output
              })
            }
