#! /usr/bin/env bash
# Copyright 2023 Nordic Semiconductor ASA
# SPDX-License-Identifier: Apache-2.0

set -eu

function display_help(){
  echo "\
_generate_coverage_report.sh [-help]
  Generate an html coverage report for BabbleSim tests

  You can call it from the Zephyr top level as:
    tests/bsim/_generate_coverage_report.sh

  Coverage files will be searched for in the folder pointed by
  the variable WORK_DIR which by default is
  ${ZEPHYR_BASE}/bsim_out

  By default the output will be placed in \${WORK_DIR}/lcov_html/.
  You can override this by setting the variable OUTPUT_DIR

  By default it takes all coverage information generated by all run tests
  but you can limit the search by setting WORK_DIR to some subfolder

  You can also merge in the twister coverage report by setting
  the variable TWISTER_COVERAGE_FILE, for example as:
  TWISTER_COVERAGE_FILE=\${ZEPHYR_BASE}/twister-out/coverage.info
  after having run twister, for example as
  twister -p nrf52_bsim -T tests/bluetooth/ --coverage

  Note: Generating a coverage report for many tests is a lengthy process
"
}

# Parse command line
if [ $# -ge 1 ]; then
  if grep -Eiq "(\?|-\?|-h|help|-help|--help)" <<< $1 ; then
    display_help
    exit 0
  fi
fi

WORK_DIR="${WORK_DIR:-${ZEPHYR_BASE}/bsim_out}"
OUTPUT_DIR="${OUTPUT_DIR:-${WORK_DIR}}"
TWISTER_COVERAGE_FILE="${TWISTER_COVERAGE_FILE:-""}"

lcov --capture --directory ${WORK_DIR} --output-file ${OUTPUT_DIR}/coverage.pre.info \
  -q --rc lcov_branch_coverage=1
lcov --remove ${OUTPUT_DIR}/coverage.pre.info *generated* \
  --output-file ${OUTPUT_DIR}/coverage.info -q --rc lcov_branch_coverage=1
genhtml ${OUTPUT_DIR}/coverage.info ${TWISTER_COVERAGE_FILE} --output-directory \
   ${OUTPUT_DIR}/lcov_html -q --ignore-errors source --branch-coverage --highlight --legend

echo -e "\033[0;32mGenerated: ${OUTPUT_DIR}/lcov_html/index.html\033[0m"
