on:
  push:
    branches:
      - main
      - master
  pull_request:
      types: [opened, synchronize, reopened]

name: Code Quality & Security Scan
jobs:
  tflint:
    name: TFLint
    runs-on: ubuntu-latest
    steps:
    - name: Checking out
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Setup TFLint
      uses: terraform-linters/setup-tflint@v4
      with:
        tflint_version: latest

    - name: Initialize TFLint
      working-directory: terraform
      run: tflint --init

    - name: Run TFLint
      working-directory: terraform
      run: tflint --format compact

  tfsec:
    name: Tfsec Security Scan
    runs-on: ubuntu-latest
    needs: tflint
    steps:
    - name: Checking out
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Run Tfsec
      uses: aquasecurity/tfsec-action@v1.0.3
      with:
        working_directory: terraform
        format: default
        soft_fail: false

  checkov:
    name: Checkov Security Scan
    runs-on: ubuntu-latest
    needs: tfsec
    steps:
    - name: Checking out
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Run Checkov
      uses: bridgecrewio/checkov-action@v12
      with:
        directory: terraform
        framework: terraform
        output_format: cli
        soft_fail: false

  terraform-validate:
    name: Terraform Validate
    runs-on: ubuntu-latest
    needs: checkov
    steps:
    - name: Checking out
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Setup Terraform
      uses: hashicorp/setup-terraform@v3
      with:
        terraform_version: latest

    - name: Terraform Format Check
      working-directory: terraform
      run: terraform fmt -check -recursive

    - name: Terraform Init (for validation)
      working-directory: terraform
      env:
        TF_VAR_vault_address: "https://vault.example.com:8200"
        TF_VAR_environment: "test"
        TF_VAR_short_hostname: "test-host"
        TF_VAR_role_id: "dummy-role-id"
        TF_VAR_secret_id: "dummy-secret-id"
      run: terraform init -backend=false

    - name: Terraform Validate
      working-directory: terraform
      env:
        TF_VAR_vault_address: "https://vault.example.com:8200"
        TF_VAR_environment: "test"
        TF_VAR_short_hostname: "test-host"
        TF_VAR_role_id: "dummy-role-id"
        TF_VAR_secret_id: "dummy-secret-id"
      run: terraform validate

  sonarqube:
    name: SonarQube Trigger
    runs-on: ubuntu-latest
    needs: terraform-validate
    steps:
    - name: Checking out
      uses: actions/checkout@v4
      with:
        # Disabling shallow clone is recommended for improving relevancy of reporting
        fetch-depth: 0
    - name: SonarQube Scan
      uses: sonarsource/sonarqube-scan-action@v6
      env:
        SONAR_HOST_URL: ${{ secrets.SONARQUBE_HOST }}
        SONAR_TOKEN: ${{ secrets.SONARQUBE_TOKEN }}
