name: Terraform validation

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - "release/**"
    paths:
      - "**.tf"
      - "**.lock.hcl"
  pull_request:
    paths:
      - "**.tf"
      - "**.lock.hcl"

jobs:
  tfsec:
    name: terraform
    runs-on: ubuntu-22.04
    steps:
      - name: Checkout
        uses: actions/checkout@755da8c3cf115ac066823e79a1e1788f8940201b # v3.2.0
        with:
          ref: ${{ !github.event.pull_request.head.repo.fork && github.head_ref || '' }}

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@633666f66e0061ca3b725c73b2ec20cd13a8fdd1 # tag=v2.0.3

      - name: Terraform format and validate
        shell: bash
        run: |
          dirs=$(find . -type f -name "*.tf" -exec dirname "{}" \; | sort -ud)
          result=0
          for dir in $dirs; do
            echo "Checking $dir"
            terraform -chdir="$dir" init || result=1
            terraform -chdir="$dir" fmt -check=true -diff=true || result=1
            terraform -chdir="$dir" validate -no-color || result=1
          done
          exit $result

      - name: Check HCL lock files are up to date
        id: hcl-lock
        shell: bash
        run: |
          dirs=$( find . -type f -name "*.lock.hcl" -exec dirname "{}" \; | sort -ud)
          for dir in $dirs; do
            echo "Checking $dir"
            terraform -chdir="$dir" init
            terraform -chdir="$dir" providers lock -platform=linux_arm64 -platform=linux_amd64 -platform=darwin_arm64 -platform=darwin_amd64 -platform=windows_amd64
          done
          git diff --exit-code

      - name: Push changes on renovate
        if: ${{ failure() && (steps.hcl-lock.conclusion == 'failure') && startsWith(github.head_ref, 'renovate/') }}
        shell: bash
        run: |
          git config --global user.name "renovate[bot]"
          git config --global user.email "29139614+renovate[bot]@users.noreply.github.com"
          git commit -am "[bot] Update HCL lock files"
          git push
