#!/bin/bash

# This script uses separate git worktree (created if doesn't exist) to build
# with with coverage support and collect it using uncov.
#
# Doesn't process arguments.

set -e

# path to worktree that measures coverage relative to repository location
coverage_path=../vifm-coverage

# cd to the root of the repository
cd "$(dirname "$(readlink -f "$0")")/.."

original_worktree=$(readlink -f .)
coverage_worktree=$(readlink -f "$coverage_path")

branch="$(basename "$(git symbolic-ref HEAD 2> /dev/null)")"
if [ -z "$branch" ]; then
    branch="no-branch"
fi

git stash save --include-untracked 'temporary stash of uncov-coverage script'
git stash apply --index

if [ -d "$coverage_worktree" ]; then
    cd "$coverage_worktree/src"
else
    git worktree add --detach "$coverage_worktree"
    cd "$coverage_worktree"
    ./configure --enable-coverage CFLAGS=-O0
    cd src
fi

git clean --force -d ..
git checkout --force stash@{0}^
git stash pop

# need to remove *.gcda in tests as well, otherwise libgcov in tests that fork
# can print "overwriting an existing profile data with a different timestamp" to
# error stream and break tests
find . ../tests -name '*.gcda' -delete

make -C ../tests build
make check

uncov new-gcovi --capture-worktree \
                --prefix src \
                --exclude src/lua/lua \
                --exclude src/utils/parson.c \
                --exclude src/utils/xxhash.c \
                --exclude src/utils/utf8proc.c \
                "$coverage_worktree/src"
