name: Terraform
on:
  workflow_call:

env:
  # mark:automatic-version
  VERSION: "1.0.0"

jobs:
  plan-deploy:
    runs-on: ubuntu-22.04
    permissions:
      contents: read
      pull-requests: write
    env:
      TF_CLOUD_ORGANIZATION: "firezone"
      TF_API_TOKEN: "${{ secrets.TF_API_TOKEN }}"
      TF_WORKSPACE: "staging"
    steps:
      - name: Get Terraform Version
        run: |
          TERRAFORM_VERSION=$(cat .tool-versions | grep terraform | awk '{ print $NF; }')
          echo "TERRAFORM_VERSION=${TERRAFORM_VERSION}" >> $GITHUB_ENV
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: ${{ env.TERRAFORM_VERSION }}
      - uses: actions/checkout@v4
      - name: Validate cloud-init
        run: |
          sudo apt-get install -y cloud-init
          sudo cloud-init schema --config-file terraform/modules/relay-app/templates/cloud-init.yaml
          sudo cloud-init schema --config-file terraform/modules/elixir-app/templates/cloud-init.yaml
          sudo cloud-init schema --config-file terraform/modules/gateway-google-cloud-compute/templates/cloud-init.yaml
      - name: Check Formatting
        working-directory: terraform
        run: |
          terraform fmt --check --recursive
      - name: Upload Configuration
        uses: hashicorp/tfc-workflows-github/actions/upload-configuration@v1.1.1
        id: plan-upload
        with:
          workspace: ${{ env.TF_WORKSPACE }}
          # Subdirectory is set in the project settings:
          # https://app.terraform.io/app/firezone/workspaces/staging/settings/general
          directory: "./"
          speculative: true
      - name: Create Plan Run
        uses: hashicorp/tfc-workflows-github/actions/create-run@v1.1.1
        id: plan-run
        env:
          TF_VAR_image_tag: '"${{ env.VERSION }}-${{ github.sha }}"'
        with:
          workspace: ${{ env.TF_WORKSPACE }}
          configuration_version:
            ${{ steps.plan-upload.outputs.configuration_version_id }}
          plan_only: true
      - name: Get Plan Output
        uses: hashicorp/tfc-workflows-github/actions/plan-output@v1.1.1
        id: plan-output
        with:
          plan: ${{ fromJSON(steps.plan-run.outputs.payload).data.relationships.plan.data.id }}
      - name: Update PR
        uses: actions/github-script@v7
        id: plan-comment
        if: ${{ github.event_name == 'pull_request' }}
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            // 1. Retrieve existing bot comments for the PR
            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 Cloud Plan Output')
            });
            const output = `#### Terraform Cloud Plan Output

            \`\`\`
            Plan: ${{ steps.plan-output.outputs.add }} to add, ${{ steps.plan-output.outputs.change }} to change, ${{ steps.plan-output.outputs.destroy }} to destroy.
            \`\`\`

            [Terraform Cloud Plan](${{ steps.plan-run.outputs.run_link }})
            `;
            // 3. Update previous comment or create new one
            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
              });
            }
