name: Continuous Integration

on:
  push:
    branches:
      - '**'
  pull_request:
    branches:
      - '**'
  workflow_dispatch:

permissions:
  contents: read
  id-token: write
  security-events: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Check out code
      uses: actions/checkout@v6
      with:
        fetch-depth: 0

    - name: Get Go version
      run: |
        version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2)
        echo "version=${version}" >> "$GITHUB_OUTPUT"
      id: go-version

    - name: Set up Go
      uses: actions/setup-go@v6
      with:
        go-version: ${{ steps.go-version.outputs.version }}
        check-latest: true

    - name: Install golangci-lint
      uses: golangci/golangci-lint-action@v9
      with:
        install-only: true
        version: v2.11.4 # renovate: datasource=github-tags depName=golangci/golangci-lint

    - name: Verify Code Generation
      run: |
        make verify-generate

    - name: Lint
      run: |
        make lint

    - name: Build
      if: (!startsWith(github.head_ref, 'release'))
      run: |
        make build

    # For release testing
    - name: Build All
      if: github.base_ref == 'master' && startsWith(github.head_ref, 'release')
      run: |
        make release

    - name: Test
      env:
        COVER: true
      run: |
        make test

    - name: Generate Coverage Report
      if: github.event_name == 'push'
      run: |
        go install github.com/jandelgado/gcov2lcov@25681830fb515e3d4c117e136b4f049e21efb4d0
        gcov2lcov -infile=c.out -outfile=lcov.info

    - name: Upload Coverage Report
      if: github.event_name == 'push'
      uses: qltysh/qlty-action/coverage@v2
      with:
        oidc: true
        files: lcov.info

    - name: Run Trivy vulnerability scanner
      if: (!startsWith(github.head_ref, 'release'))
      uses: aquasecurity/trivy-action@0.35.0
      with:
        scan-type: 'rootfs'
        scan-ref: './oauth2-proxy'
        severity: 'CRITICAL,HIGH'
        hide-progress: true
        format: 'sarif'
        output: 'trivy-results.sarif'
        exit-code: '0'

    - name: Upload Trivy scan results
      if: (!startsWith(github.head_ref, 'release'))
      uses: github/codeql-action/upload-sarif@v4
      with:
        sarif_file: 'trivy-results.sarif'

  docker:
    runs-on: ubuntu-latest
    steps:
    - name: Check out code
      uses: actions/checkout@v6
      with:
        fetch-depth: 0

    - name: Set up QEMU
      uses: docker/setup-qemu-action@v3
    
    - name: Set up Docker Buildx
      id: buildx
      uses: docker/setup-buildx-action@v3

    - name: Docker Build
      if: (!startsWith(github.head_ref, 'release'))
      run: |
        make build-docker

    # For release testing
    - name: Docker Build All
      if: github.base_ref == 'master' && startsWith(github.head_ref, 'release')
      run: |
        make build-docker-all
