#!/bin/sh
# $Id: check-ncu-pconfig,v 1.9 2025/01/12 17:01:11 tom Exp $
# check if ncurses*-config matches ncurses*.pc

PROG=ncurses

HERE=misc
PATH=`pwd`:$PATH
export PATH

mytemp=`mktemp -d`
[ -d "$mytemp" ] || failed "mktemp"
trap 'rm -rf $mytemp; exit 1' 1 2 3 15
trap 'rm -rf $mytemp' 0

TRIMBLANKS=$mytemp/trimblanks.sed
SCRIPT_LOG=$mytemp/with-script.log
CONFIG_LOG=$mytemp/with-pconfig.log

cat >"$TRIMBLANKS" <<"EOF"
s/^[ 	]*//
s/[ 	]*$//
s/[ 	][ 	]*/ /g
EOF

failed() {
	echo "? $*" >&2
	exit 1
}

sort_options() {
	"$@" | tr ' ' '\n' | sort -u | tr '\n' ' ' | sed -f $TRIMBLANKS
	echo
}

report_script() {
	NCFG=$HERE/"$PROG"-config
	if [ -s "$NCFG" ]
	then
		chmod +x "$NCFG"
		for ncfg in \
			cflags cflags-only-I cflags-only-other \
			libs libs-only-l libs-only-L libs-only-other
		do
			echo ".. $ncfg"
			sort_options $NCFG --$ncfg
		done
	fi
}

report_pconfig() {
	for npkg in "$@"
	do
		# The wildcard is only to handle ncursesw vs ncursesw6 vs ncursesw6tw.
		# Ignore matches on the C++ binding.
		case $npkg in
		*++*)	continue;;
		esac
		[ -s "$npkg" ] || continue
		NPKG=`basename "$npkg" .pc`
		for ncfg in \
			cflags cflags-only-I cflags-only-other \
			libs libs-only-l libs-only-L libs-only-other
		do
			echo ".. $ncfg"
			PKG_CONFIG_PATH=`pwd`/$HERE sort_options pkg-config "$NPKG" --"$ncfg" | sed -e 's/ $//'
		done
	done
}

not_build_tree() {
	failed "not in $PROG build-tree"
}

case `pwd` in
*/"$PROG"*)
	[ -d $PROG ] || not_build_tree
	[ -d misc ] || not_build_tree
	;;
*)
	not_build_tree
	;;
esac

report_script >"$SCRIPT_LOG"
report_pconfig $HERE/*"$PROG"*.pc >"$CONFIG_LOG"

if [ -s "$CONFIG_LOG" ]
then
	echo "..report_script:"
	cat "$CONFIG_LOG"
	if [ -s "$SCRIPT_LOG" ]
	then
		cat "$SCRIPT_LOG"
		if cmp -s "$CONFIG_LOG" "$SCRIPT_LOG"
		then
			echo "..same:"
		else
			echo "..diff:"
			diff -u "$CONFIG_LOG" "$SCRIPT_LOG" | \
				sed -e "s,$mytemp/,,g" \
					-e 's/	.*//'
		fi
		echo "..report_pconfig:"
		report_pconfig $HERE/*"$PROG"*.pc
	fi
elif [ -s "$SCRIPT_LOG" ]
then
	cat "$SCRIPT_LOG"
fi
# vile:ts=4 sw=4
