#!/bin/bash -e

for path in /usr/lib/llvm-3.9/lib/clang/3.9.[0-9]/lib/linux/; do LLVM_PATH=$path; done
export OPTIONS="-Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Zno-landing-pads -L$LLVM_PATH -lclang_rt.profile-x86_64"
export COVERAGE_OPTIONS="-Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Cpasses=insert-gcov-profiling -Zno-landing-pads -L$LLVM_PATH -lclang_rt.profile-x86_64"
export CARGO_INCREMENTAL=0

LCOVOPT="--gcov-tool ./ci/llvm-gcov --rc lcov_branch_coverage=1 --rc lcov_excl_line=assert"
LCOV="/usr/local/bin/lcov"

# cleanup all
rm -rf *.info *.gcda *.gcno
cargo clean

# unit tests of gbdt
export RUSTC_WRAPPER="./ci/gbdt-cov-rustc"
cargo rustc --package gbdt --all-features --profile test --lib
rm ./target/debug/gbdt-*.d
./target/debug/gbdt-*
${LCOV} ${LCOVOPT} --capture --directory . --base-directory . -o unittest.info

# cleanup target
rm -rf *.gcda *.gcno
cargo clean

# integration tests
export RUSTC_WRAPPER="./ci/gbdt-cov-rustc"
cargo rustc --all-features --examples
find target/debug/examples -executable -type f -exec ./{} \; > /dev/null
${LCOV} ${LCOVOPT} --capture --directory . --base-directory . -o examples.info

# combining and filtering
${LCOV} ${LCOVOPT} --add unittest.info --add examples.info -o coverage.info
${LCOV} ${LCOVOPT} --extract coverage.info `find "$(cd src; pwd)" -name "*.rs"` -o final.info

# generate report if not in CI
if [[ "$CI" != true ]]; then
  genhtml --branch-coverage --demangle-cpp --legend final.info -o target/coverage/ --ignore-errors source
fi
