#!/bin/sh
#
# SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
# SPDX-License-Identifier: BSD-2-Clause

skip_all()
{
	local first="$1" last="$2" reason="$3"
	local idx="$first"
	while [ "$idx" -le "$last" ]; do
		echo "ok $idx # skip $reason"
		idx=$((idx + 1))
	done
}

[ -z "$CONFGET" ] && CONFGET='./confget'
[ -z "$TESTDIR" ] && TESTDIR='t'

T5="$TESTDIR/t5.ini"

echo '1..8'

if [ ! -f "$T5" ]; then
	echo "Bail out!  No test file $T5"
	exit 255
fi

if ! $CONFGET -qfeatures | tr ' ' '\n' | grep -Eqe '^REGEX='; then
	skip_all 1 9 'No regular expression support in confget'
	exit 0
fi

singloc="$(locale -a | grep -Eie '\.iso-?8859-?(1|15)([^0-9]|$)' | head -n1)"
if [ -z "$singloc" ]; then
	skip_all 1 8 'No ISO-8859-1 or ISO-8859-15 locale configured'
	exit 0
fi
echo "# Using '$singloc' as a single-byte locale name"

u8loc="$(locale -a | grep -Eie '\.utf-?8([^0-9]|$)' | head -n1)"
if [ -z "$u8loc" ]; then
	skip_all 1 8 'No UTF-8 locale configured'
	exit 0
fi
echo "# Using '$u8loc' as a multibyte locale name"

# In a non-UTF-8 environment, that letter should be treated as two characters.
if env "LC_ALL=$singloc" $CONFGET -f "$T5" -s 'latin' -x -l -N -m '^..$' | grep -Eqe '^enye='; then echo 'ok 1'; else echo "not ok 1rc $?"; fi
if ! env "LC_ALL=$singloc" $CONFGET -f "$T5" -s 'latin' -x -l -N -m '^.$' | grep -Eqe '^enye='; then echo 'ok 2'; else echo "not ok 2 rc $?"; fi

if env "LC_ALL=$singloc" $CONFGET -f "$T5" -s 'latin' -l -N -m '??' | grep -Eqe '^enye='; then echo 'ok 3'; else echo "not ok 3 rc $?"; fi
if ! env "LC_ALL=$singloc" $CONFGET -f "$T5" -s 'latin' -l -N -m '?' | grep -Eqe '^enye='; then echo 'ok 4'; else echo "not ok 4 rc $?"; fi

# In a UTF-8 environment, that letter should be treated as a single character.
if ! env "LC_ALL=$u8loc" $CONFGET -f "$T5" -s 'latin' -x -l -N -m '^..$' | grep -Eqe '^enye='; then echo 'ok 5'; else echo "not ok 5 rc $?"; fi
if env "LC_ALL=$u8loc" $CONFGET -f "$T5" -s 'latin' -x -l -N -m '^.$' | grep -Eqe '^enye='; then echo 'ok 6'; else echo "not ok 6 rc $?"; fi

if $CONFGET -q features | grep -Fqe ' REGEX_IMPL_C_'; then
	# Skipped because of a GNU libc fnmatch() bug, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1024974
	echo 'ok 7 # skip GNU libc fnmatch bug'
else
	if ! env "LC_ALL=$u8loc" $CONFGET -f "$T5" -s 'latin' -l -N -m '??' | grep -Eqe '^enye='; then echo 'ok 7'; else echo "not ok 7 rc $?"; fi
fi
if env "LC_ALL=$u8loc" $CONFGET -f "$T5" -s 'latin' -l -N -m '?' | grep -Eqe '^enye='; then echo 'ok 8'; else echo "not ok 8 rc $?"; fi
