name: Coverage

on:
  workflow_dispatch:
  push:
    branches:
      - master
      - develop
      - fixes
      - release/*
  pull_request:
    branches:
      - master
      - develop
      - fixes
      - release/*

jobs:
  coverage:
    runs-on: ubuntu-latest

    steps:
    - run: |
        sudo apt-get update
        sudo apt-get install -y \
            cmake \
            docbook-xsl \
            lcov \
            libargon2-dev \
            libc-ares-dev \
            libcjson-dev \
            libcjson1 \
            libcunit1-dev \
            libedit-dev \
            libgmock-dev \
            libmicrohttpd-dev \
            libssl-dev \
            libwrap0-dev \
            microsocks \
            ninja-build \
            python3-all \
            python3-paho-mqtt \
            python3-psutil \
            uthash-dev \
            xsltproc

    - uses: actions/checkout@v6

    - name: Configure
      run: |
        cmake \
          -G Ninja \
          -DCMAKE_BUILD_TYPE=Debug \
          -S . \
          -B build
      env:
        CFLAGS: "-coverage -O0 -Wall -ggdb -fprofile-arcs -fprofile-dir=${{github.workspace}}/coverage.%p"
        CXXFLAGS: "-coverage -O0 -Wall -ggdb -fprofile-arcs -fprofile-dir=${{github.workspace}}/coverage.%p"
        LDFLAGS: "-coverage"

    - name: Build
      run: cmake --build build --parallel $(nproc)

    - name: Tests
      working-directory: build/
      run: ctest -j20 --resource-spec-file ../test/resource.json --output-on-failure --repeat until-pass:5

    - name: Merge GCDA files
      run: test/merge-gcda.py

    - name: Generate coverage data
      run: |
        lcov --capture --directory . --output-file coverage.info --no-external --exclude test/ --exclude deps/ --exclude include/

    - name: Update to Codecov
      uses: codecov/codecov-action@v6
      with:
        token: ${{ secrets.CODECOV_TOKEN }}
        fail_ci_if_error: true
        files: ./coverage.info
        verbose: true
