#!/bin/sh
#
# Search for XL C/C++, CLANG or GCC, with this priority
#
# In the Makefile check the value of $(CC) (e.g. "ifeq ($(CC),gcc)")
# to define specific compiler configurations
#
#set -x

if [ -n "$CC" ]; then
	# If compiler is specified look for the path
	CCPATH=$(which "$CC" 2>&1)
	if [ -n "${CCPATH%%/*}" ]; then
		echo "Unable to find $CC, will search for a compatible compiler ..."
		CC=
	fi
fi

if [ -z "$CC" ]; then
	CCS="xlc_r clang gcc"

	#
	# Look for supported compilers
	#
	for c in $CCS; do
		if CCPATH=$(which "$c" 2>&1) && [ -z "${CCPATH%%/*}" ] && (echo "#include <sys/socket.h>" | $c -fsyntax-only -x c - > /dev/null 2>&1); then
			CC="$c"
			break
		fi
	done
fi

STAMP=configure-stamp
#[ -f $STAMP ] && exit 0

#
# Make a link to a proper Makefile.*
#
if [ -z "$CC" ]; then
	echo "Unable to find GNU GCC, IBM XL C/C++ or clang. Fix your PATH!"
	exit 1
else
	echo "Using $CCPATH to compile Cntlm"
	echo "$CC" > $STAMP
fi

CONFIG=config/config.h
TESTS="endian gethostname socklen_t strdup arc4random_buf strlcat strlcpy memset_s gss"

rm -f $CONFIG
echo "#ifndef CONFIGURE_CONFIG_H" > $CONFIG
echo "#define CONFIGURE_CONFIG_H" >> $CONFIG
echo "" >> $CONFIG
for i in $TESTS; do
	printf "Checking %s... " "$i"
	printf "#define config_%s " "$i" >> $CONFIG
	$CC -std=c99 -D__BSD_VISIBLE -D_ALL_SOURCE -D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200112 -D_ISOC99_SOURCE -D_REENTRANT -D_BSD_SOURCE -D_DEFAULT_SOURCE -D_DARWIN_C_SOURCE -o config/"$i" config/"$i".c 2> /dev/null
	rc=$?

	if [ $rc -ne 0 ]; then # -o -n "$OUT" ]; then
		rc=0
		RET=no
	else
		RET=$(./config/"$i")
		rc=$?
		[ -z "$RET" ] && if [ $rc -eq 0 ]; then RET="no"; else RET=yes; fi
	fi

	echo $rc >> $CONFIG
	echo "$RET"
done

while [ "$1" ]
do
	case $1 in
		--enable-static)
			printf "#define ENABLE_STATIC" >> $CONFIG
			echo "" >> $CONFIG
			;;
		*)
			echo "Unknown flag $1"
			rm -f $CONFIG
			;;
	esac
	shift
done
if [ -f $CONFIG ]; then
	echo "" >> $CONFIG
	echo "#endif // CONFIGURE_CONFIG_H" >> $CONFIG
fi
