#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2016-2022, Intel Corporation

#
# src/test/unicode_api/TEST0 -- unicode C API check
#

. ../unittest/unittest.sh

require_test_type medium
require_command bc

require_fs_type any
# there's no point in testing different builds
require_build_type debug
require_command clang

SRC=../..
HEADERS_DIR=$SRC/include
EXC_PATT="set_funcs|strdup"
FAILED=0
DEF_COL=6

function pick_col {
	require_command bc
	local ver=$(clang --version | grep version | sed "s/.*clang version \([0-9]*\)\.\([0-9]*\).*/\1*100+\2*10/" | bc)
	if [ $ver -le 340 ]; then
		DEF_COL=5
	fi
}

function check_file {
	local file=$1
	local h_dir=$2
	local pat=$3

	local funcs=$(clang -Xclang -ast-dump -I$HEADERS_DIR $file -fno-color-diagnostics 2> /dev/null |\
		grep "FunctionDecl.*pmem.*char \*" | cut -d " " -f $DEF_COL)
	for func in $funcs
	do
		local good=1	# Not starting at 0 allows set -e
		to_check="$h_dir/*.h $h_dir/*/*.h"
		if [ -n "${pat:+x}" ] && [[ $func =~ $pat ]]; then
			continue
		fi

		for f in $to_check
		do
			let good+=$(grep -c "$func[UW][ ]*(" $f)
		done
		if [ $good -ne 3 ]; then
			echo "Function $func in file $file does not have unicode U/W counterparts"
			FAILED=1;
		fi
	done
}

setup

pick_col

for f in $HEADERS_DIR/*.h
do
	check_file $f $HEADERS_DIR $EXC_PATT
done

if [ $FAILED -ne 0 ]; then
	exit 1
fi

pass
