#!/usr/bin/env bash

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

LLVM_COV=""

verlte() {
    [  "$1" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]
}

verlt() {
    [ "$1" = "$2" ] && return 1 || verlte $1 $2
}

check_llvm_cov() {
    if [ -z `which $1` ];
    then
        return
    else
        p=$(which $1)
        verinfo=`${p} --version`
        first_word=$(echo ${verinfo} | awk "{ print \$1 }")
        gcov_ver=$(echo ${verinfo} | awk "{ print \$4 }")
        llvm_cov_ver=$(echo ${verinfo} | awk "{ print \$5 }")

        if [ "$first_word" = "gcov" ]; then
            echo "gcov detected, ver = " ${gcov_ver}
            verlt "${gcov_ver}" "8.0.0" && LLVM_COV=$1 || LLVM_COV=""
            return
        elif [ "$first_word" = "LLVM" ]; then
            echo "llvm-cov detected, ver = " ${llvm_cov_ver}
            verlte "11.0.0" "${gcov_ver}" && LLVM_COV="$1 gcov" || LLVM_COV=""
            return
        else
            echo "neither llvm-cov or gcov ... skipping"
            return
        fi
    fi
}

# search priority
for c in "llvm-cov-11" "gcov-7" "llvm-cov" "gcov"
do
    check_llvm_cov $c
    if [[ ! -z "${LLVM_COV}" ]];
    then
        break
    fi
done

if [[ -z "${LLVM_COV}" ]];
then
    echo "You need gcov < 8.0, or llvm-cov >= 11.0 to analyze Rust generated gcno/gcda files! See Readme.md for more details."
    exit 1
fi

${LLVM_COV} $*
