name: "Terraform"

on:
  workflow_dispatch:
  # TODO: enable it back when migration is completed.
  push:
    branches:
      - main
    paths:
      - "infra/terraform/**"
  pull_request:
    branches:
      - main
    paths:
      - "infra/terraform/**"

jobs:
  terraform:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      pull-requests: write
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - name: Harden the runner (Audit all outbound calls)
        uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
        with:
          egress-policy: audit

      - name: Checkout
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

      - name: Tailscale
        uses: tailscale/github-action@v3
        with:
          oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }}
          oauth-secret: ${{ secrets.TS_OAUTH_SECRET }}
          tags: tag:github

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@f24d7193d98baebaeacc7e2227925dd47cc267f5 # v4.2.0
        with:
          role-to-assume: ${{ secrets.AWS_ASSUME_ROLE_ARN }}
          aws-region: "eu-central-1"

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3.1.2

      - name: Terraform Format
        id: fmt
        run: terraform fmt -check -recursive
        continue-on-error: true
        working-directory: infra/terraform

      - name: Terraform Init
        id: init
        run: terraform init
        working-directory: infra/terraform

      - name: Terraform Validate
        id: validate
        run: terraform validate
        working-directory: infra/terraform

      - name: Terraform Plan
        id: plan
        run: terraform plan -out .planfile
        working-directory: infra/terraform

      - name: Post PR comment
        uses: borchero/terraform-plan-comment@434458316f8f24dd073cd2561c436cce41dc8f34 # v2.4.1
        if: always() && github.ref != 'refs/heads/main' && (steps.plan.outcome == 'success' || steps.plan.outcome == 'failure')
        with:
          token: ${{ github.token }}
          planfile: .planfile
          working-directory: "infra/terraform"

      - name: Terraform Apply
        id: apply
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform apply .planfile
        working-directory: "infra/terraform"
