# in projects where [ $mb_use_custom_cfgdefs = yes ],
# cfgdefs.sh is invoked from within ./configure via
# . $mb_project_dir/project/cfgdefs.sh

# a successful return from cfgdefs.sh will be followed
# by a second invocation of the config_copy() function,
# reflecting any changes to common config variables
# made by cfgdefs.sh.

# finally, cfgdefs.sh may update the contents of the
# build-time-generated cfgdefs.mk.

# cfgdefs helper functions
. "$mb_project_dir/project/config/cfghost.sh"


# no custom switches yet
for arg ; do
	case "$arg" in
		*)
			error_msg ${arg#}: "unsupported config argument."
			exit 2
	esac
done


cfgdefs_set_cfghost_flavors()
{
	cfghost_set_target_cfghost
	cfghost_set_native_cfghost
}

# cfghost
cfgdefs_set_cfghost_flavors

# system tests: target
mb_cfgdefs_cc=$(make -s -f Makefile.tmp .display-cc)
mb_cfgdefs_cflags=$(make -s -f Makefile.tmp .display-cflags)

printf '\n\n#system tests: target\n' >> $mb_pwd/cfgdefs.mk

# <stropts.h>
$mb_cfgdefs_cc $mb_cfgdefs_cflags -E -xc - \
	--include=stropts.h < /dev/null    \
	> /dev/null 2>/dev/null ||         \
		printf 'CFLAGS_CONFIG\t\t+= -DHAVE_NO_STROPTS_H\n' \
			>> $mb_pwd/cfgdefs.mk

# openssl 1.1 or newer or a compatible libressl
printf 'void * addr = &X509_NAME_ENTRY_set;'           \
	| $mb_cfgdefs_cc $mb_cfgdefs_cflags            \
		--include=openssl/x509.h -S -xc - -o - \
		> /dev/null 2>/dev/null &&             \
	printf 'CFLAGS_CONFIG\t\t+= -DOPENSSL_VERSION_1_1\n' \
		>> $mb_pwd/cfgdefs.mk

# ncurses: python refers to the internals of typedef struct _win_st WINDOW
printf 'CFLAGS_CONFIG\t\t+= -DNCURSES_INTERNALS\n' >> $mb_pwd/cfgdefs.mk

# ncurses: tinfo
mb_ncurses_libs="-lpanelw -lncursesw"

if [ $mb_disable_shared = 'yes' ]; then
	printf 'int main(void){return 0;}'          \
		| $mb_cfgdefs_cc $mb_cfgdefs_cflags \
			-ltinfo -o a.out -xc -      \
			< /dev/null 2>/dev/null     \
		&& mb_ncurses_libs="$mb_ncurses_libs -ltinfo"
else
	$mb_cfgdefs_cc $mb_cfgdefs_cflags               \
			-shared -ltinfo -o a.out -xc -  \
			< /dev/null 2>/dev/null         \
		&& mb_ncurses_libs="$mb_ncurses_libs -ltinfo"
fi

printf 'LDFLAGS_NCURSES_LIBS\t+= %s\n' "$mb_ncurses_libs" \
	>> $mb_pwd/cfgdefs.mk


# system tests: (native) pycompile
printf '\n\n#system tests: (native) pycompile\n' >> $mb_pwd/cfgdefs.mk

$mb_native_cc -E -xc -                     \
	--include=stropts.h < /dev/null    \
	> /dev/null 2>/dev/null ||         \
		printf 'PYCOMPILE_CFLAGS\t+= -DHAVE_NO_STROPTS_H\n' \
			>> $mb_pwd/cfgdefs.mk

# ncurses: tinfo
mb_ncurses_libs="-lpanelw -lncursesw"

printf 'int main(void){return 0;}'        \
	| $mb_native_cc                   \
		-ltinfo -o a.out -xc -    \
		< /dev/null 2>/dev/null   \
	&& mb_ncurses_libs="$mb_ncurses_libs -ltinfo"

printf 'PYCOMPILE_NCURSES_LIBS\t+= %s\n' "$mb_ncurses_libs" \
	>> $mb_pwd/cfgdefs.mk


# clean-up
rm -f a.out


# all done
return 0
