#!/bin/bash
# Adrien 'Adriweb' Bertrand
# Tool to generate a list of things that are used/tested in the toolchain example codes.
# Thanks to jacobly for the sed trick

set -ex

# Grab current path
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Let's go back to the root of the toolchain
cd $DIR/../

# All header files we want to extract prototypes from
libraries="fileioc fontlibc graphx keypadc"

# The destination markdown file
outfile=$DIR/tested-list.md

# Find once the example sources we'll be searching in
exampleFiles=$(find ./examples -type f \( -iname '*.c' -o -iname '*.cpp' -o -iname '*.h' -o -iname '*.hpp' -o -iname '*.asm' \))
testFiles=$(find ./test -type f \( -iname '*.c' -o -iname '*.cpp' -o -iname '*.h' -o -iname '*.hpp' -o -iname '*.asm' \))

echo "## List of tested functions" > $outfile

for library in $libraries
do
    echo -e "\n### $library" >> $outfile
    echo -e "| Function | Tested? | Occurrences |" >> $outfile
    echo -e "| -------- | ------- | ----------- |" >> $outfile

    # This will produce a list of funcName:funcLine, which we'll parse in the for loop below.
    filefuncts=$(sed -nse 's/^\s*export\s\+\(\w\+\)$/\1/;Ts;p;=;:s' src/$library/*.asm | sed -e 'N;s/\n/:/')
    totalFuncs=0
    totalTested=0
    for funcAndLine in $filefuncts
    do
        : $((totalFuncs++))
        func=${funcAndLine%:*}
        line=${funcAndLine##*:}
        count=$(grep -l "\b${func}\s*(" ${exampleFiles} ${testFiles} | wc -l | tr -d ' ')
        if [[ $count -eq 0 ]]
        then
            foundStr="✗"
            searchLink=""
        else
            : $((totalTested++))
            foundStr="YES"
            searchLink=" [in $count file$([[ $count -eq 1 ]] || printf s)](https://github.com/search?q=${func}+repo%3ACE-Programming%2Ftoolchain+path%3Aexamples&type=Code)"
        fi
        echo -e "| [\`${func}\`](/${f}#L${line}) | $foundStr |$searchLink" >> $outfile
    done
    echo -e "\n**Total: ${totalTested}/${totalFuncs} tested.**" >> $outfile
done

echo -e "\n\n---\n*Generated by [check.sh](/test/check.sh)*" >> $outfile

cat $outfile
