#!/bin/bash
#
# A little helper to overload default datalad executables with the one ran
# through coverage

set -eu

# Paths must not use $PWD: tests invoke datalad with cwd under temp dirs, so
# $PWD/../.coveragerc would not point at the repository root (see AppVeyor/CI).
_script_dir=$(cd "$(dirname "$0")" && pwd)
_repo_root=$(cd "$_script_dir/../.." && pwd)

bin=$(basename $0)
curbin=$(which "$bin")
curdatalad=$(which datalad)
curdir=$(dirname $curdatalad)

COVERAGE_RUN="-m coverage run"
export COVERAGE_PROCESS_START=$_repo_root/.coveragerc
export PYTHONPATH="$_script_dir/"
export PATH=${PATH//$curdir:/}
newdatalad=$(which datalad)
newbin=$(which $bin)
newpython=$(sed -ne '1s/#!//gp' $newdatalad)

if [ $newdatalad = $curdatalad ]; then
   echo "E: binary remained the same: $newdatalad" >&2
   exit 1
fi

touch /tmp/coverages
export COVERAGE_FILE=/tmp/.coverage-entrypoints-$RANDOM
echo "Running now $newpython $COVERAGE_RUN --include=datalad/* -a $newbin $@" >> /tmp/coverages
#$newpython $COVERAGE_RUN --include=datalad/* -a $newbin "$@"
$newpython $COVERAGE_RUN -a $newbin "$@"
