name: Code coverage
on:
  pull_request:
  push:
    branches:
      - main

env:
  PG_VERSION: 18
  PG_PACKAGE: psp
  # Avoid failures on slow recovery
  PGCTLTIMEOUT: 120
  PG_TEST_TIMEOUT_DEFAULT: 300

jobs:
  collect:
    name: Collect and upload
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    steps:
      - name: Remove existing PostgreSQL
        run: sudo apt purge postgresql* libpq*

      - name: Clone repository
        uses: actions/checkout@v7
        with:
          submodules: recursive
          ref: ${{ github.ref }}

      - name: Install dependencies
        run: .github/scripts/ubuntu-deps.sh dev

      - name: Install PostgreSQL
        run: .github/scripts/install-postgresql.sh ${{ env.PG_PACKAGE }} ${{ env.PG_VERSION }}

      - name: Build pg_stat_monitor
        run: .github/scripts/build.sh coverage

      - name: Set permissions
        run: sudo chown -R runner:runner /var/run/postgresql

      - name: Stop existing PostgreSQL instances
        run: sudo service postgresql stop

      - name: Run tests
        run: .github/scripts/test.sh

      - name: Upload coverage data to codecov.io
        uses: codecov/codecov-action@v7
        with:
          verbose: true
          fail_ci_if_error: true
          token: ${{ secrets.CODECOV_TOKEN }}

      - name: Report on test fail
        uses: actions/upload-artifact@v4
        if: ${{ failure() }}
        with:
          name: coverage-testlog
          path: |
            regression_install
            regression_install.log
            regression.diffs
            regression.out
            results
            t/results
            tmp_check
          retention-days: 3
