#!/bin/sh
# This is free and unencumbered software released into the public domain.
# For more information, please refer to <http://unlicense.org/>
#

if ! [ -f Makefile ] ; then
	echo 'Main Makefile is missing, cannot continue'
	exit 1
fi

if ! cd $(dirname "$0") ; then
	exit 1
fi

apps_to_check=''
extra_env_vars=''
make_extra_flags='' # config_mk_extra
config_h_extra=''
config_sh_extra=''
extra_configure_opts=''
config_h_have=
config_mk_flags=
w_files_in=
sysroot=


w_new_option() # $1=opt [$2=env_variable]
{
	w_opts_configure="$w_opts_configure $1"
	w_opts_check="$w_opts_check $1"
	if [ -n "$2" ] ; then
		extra_env_vars="$extra_env_vars $2"
	fi
}

w_new_option_with()
{
	extra_packages_opts="$extra_packages_opts $1"
	w_opts_check="$w_opts_check $1"
}


if [ -f configure.project ] ; then
	. ./configure.project
fi

if [ -z "$PROJECT_TYPE" ] ; then
	PROJECT_TYPE="C++"
fi

#==========================================================

PACKAGE_NAME="${PACKAGE}"
PACKAGE_STRING="${PACKAGE} ${VERSION}"
PACKAGE_TARNAME="${PACKAGE}"
PACKAGE_BUGREPORT="${PACKAGE_URL}"
PACKAGE_VERSION="${VERSION}"

#==========================================================
# ./configure release [xz|gz|lz|bz2|zst]

if [ "$1" = "release" ] ; then
	srcdir=$(pwd)
	outdir=${PACKAGE}-${VERSION}
	cd ..
	rm -rf ${outdir}
	if [ "$2" = "dist" ] ; then
		# force creation of tarfile, copy the whole dir
		shift
		shift
		cp -rf ${srcdir} ${outdir}
		cd ${outdir}
		git clean -dfx
		rm -rf .*
		cd ..
	else
		if command -v git >/dev/null; then
			printf "Run 'git clean -dfx'? [y/N]: "
			read anzwer
			case $anzwer in y|Y)
				cd ${srcdir}
				echo '# git clean -dfx'
				git clean -dfx
				cd ..
				;;
			esac
		fi
		mkdir -p ${outdir}
		cp -rf ${srcdir}/* ${outdir}/
	fi
	#--
	echo "# tar -vcf ${outdir}.tar ${outdir}"
	tar -vcf ${outdir}.tar ${outdir}
	comp=$2
	if [ -z "$comp" ] ; then
		comp=xz
	fi
	case $comp in
		gz)  cmd=gzip    ;;
		lz)  cmd=lzip    ;;
		bz2) cmd=bzip2   ;;
		zst) cmd=zstd    ;;
		*)   cmd=${comp} ;;
	esac
	rm -f ${outdir}.tar.${comp}
	echo "# ${cmd} ${outdir}.tar"
	if ${cmd} ${outdir}.tar ; then
		echo "*** ${outdir}.tar.${comp} has been created..."
	fi
	rm -f ${outdir}.tar
	exit
fi

# w_conf/gettext: ./configure po|pot

#==========================================================

exit_error() {
	test "$1" && echo "$@"
	if [ -f config.log ] ; then
		echo "See config.log, there might be some clues there"
	fi
	rm -f config.h config.mk
	exit 1
}


check_command() # 1:<cmd> finds $1 in $PATH
{
	if [ -z "$xxpath" ] ; then
		xxpath="$(echo "$PATH" | tr ':' ' ')"
	fi
	for xcmdx in $@
	do
		case "${xcmdx}" in /*)
			# a full path, check if file is executable
			if [ -x "${xcmdx}" ] ; then
				echo "${xcmdx}"
				return 0
			fi
			continue
			;;
		esac
		#--
		for zpathz in ${xxpath}
		do
			if [ -x "${zpathz}/${xcmdx}" ] ; then
				echo "${zpathz}/${xcmdx}"
				return 0
			fi
		done
	done
	return 1
}


set_cc()
{
	CC_IS_FULL_PATH=''
	case $PROJECT_TYPE in
		C|C++) okw=1;;
		*) [ -z "$CC" ] && CC="cc"
			return ;;
	esac
	case $CC in /*)
		CC_IS_FULL_PATH=1 ;;
	esac
	GCC="no"
	if [ -n "$CC" ] ; then
		zz_list="$CC"
	else
		zz_list="cc gcc clang"
	fi
	printf "Checking for C compiler... "
	ZCC="$(check_command ${zz_list})"
	if test -z "$ZCC" ; then
		exit_error "$CC not found"
	fi
	CC="$ZCC"
	echo "$CC"
	if [ -n "$CC" ] && [ -z "$CC_IS_FULL_PATH" ] ; then
		CC="$(basename $CC)" # not a full path, keep binary name
	fi
}


set_cxx()
{
	CXX_IS_FULL_PATH=''
	if [ "$PROJECT_TYPE" != "C++" ] ; then
		[ -z "$CXX" ] && CXX="c++"
		return
	fi
	case $CXX in /*)
		CXX_IS_FULL_PATH=1 ;;
	esac
	#--
	printf "Checking for C++ compiler... "
	if [ -n "$CXX" ] ; then
		zz_list="$CXX"
	else
		zz_list="c++ g++ clang++"
	fi
	ZXX="$(check_command ${zz_list})"
	if test -z "$ZXX" ; then
		if [ -z "$CXX" ] ; then
			echo "not found" # not a fatal error
		else
			exit_error "$CXX not found"
		fi
	fi
	CXX="$ZXX"
	echo "$CXX"
	if [ -n "$CXX" ] && [ -z "$CXX_IS_FULL_PATH" ] ; then
		CXX="$(basename $CXX)" # not a full path, keep binary name
	fi
}


set_w_pkg_config()
{
	printf "Checking for pkg-config... "
	W_PKG_CONFIG=''
	if [ -n "${PKG_CONFIG}" ] ; then
		W_PKG_CONFIG="$(check_command ${PKG_CONFIG})"
		if [ -n "$W_PKG_CONFIG" ] ; then
			echo "$W_PKG_CONFIG (environment)"
			return 0
		fi
	fi
	W_PKG_CONFIG="$(check_command pkg-config pkgconf)"
	if [ -n "$W_PKG_CONFIG" ] ; then
		echo "$W_PKG_CONFIG [$($W_PKG_CONFIG --version 2>/dev/null)]"
	else
		echo "no"
		echo "WARNING: missing pkg-config: this a potentially fatal error"
	fi
}


run_pkg_config()
{
	if [ -n "$static_link" ] ; then
		pkgconfig_s='--static'
	else
		pkgconfig_s=''
	fi
	if test -n "$W_PKG_CONFIG" ; then
		${W_PKG_CONFIG} ${pkgconfig_s} "$@"
	else
		pkg-config ${pkgconfig_s} "$@"
	fi
}

w_pkgconfig_run()
{
	run_pkg_config "$@"
}


w_pkgconfig_check() # $1=<pkg> $2=[min-version]
{
	# returns 0=ok, use pkg-config
	pc_pkg="$1"
	pc_pkg_min_ver="$2"
	if [ -n "$pc_pkg_min_ver" ] ; then
		printf "Checking for %s >= %s... " "${pc_pkg}.pc" "$pc_pkg_min_ver"
	else
		printf "Checking for %s... " "${pc_pkg}.pc"
	fi
	if [ -z "$W_PKG_CONFIG" ] ; then
		echo "no (!!pkg-config is missing!!)"
		return 1
	fi
	#--
	if [ -n "$pc_pkg_min_ver" ] ; then
		run_pkg_config ${pc_pkg} --exists --atleast-version=${pc_pkg_min_ver}
	else
		run_pkg_config ${pc_pkg} --exists
	fi
	xret=$?
	if [ $xret -eq 0 ] ; then
		echo "yes [$(run_pkg_config ${pc_pkg} --modversion)]"
	else
		if [ -n "$pc_pkg_min_ver" ] ; then
			xxzzfound=$(run_pkg_config ${pc_pkg} --modversion 2>/dev/null)
			if [ -n "$xxzzfound" ] ; then
				echo "no [found $xxzzfound]"
			else
				echo "no"
			fi
		else
			echo "no"
		fi
	fi
	return $xret
}


w_compile_c_code() # $1:code  $2:extra-CFLAGS  $3:extra-LDFLAGS
{
	if [ -z "$1" ] ; then
		exit_error 'w_compile: code to compile is an empty string'
	fi
	conftest=.wxconftest$$
	printf "$1" > ${conftest}.c
	printf "\n$1" >> config.log
	echo "$CC $CFLAGS $2 ${conftest}.c -o ${conftest}.o $LDFLAGS $3" >>config.log
	$CC $CFLAGS $2 ${conftest}.c -o ${conftest}.o $LDFLAGS $3 2>>config.log
	zzzzretxx=$?
	rm -f ${conftest}.c ${conftest}.o
	return ${zzzzretxx}
}


w_check_header_and_libs() # 1:<header> 2-:[libs] is optional
{
	xheaderx=$1
	shift
	xlibsx=$@
	xretval=1
	if [ -n "$xlibsx" ] ; then
		printf "Checking for ${xheaderx} + ${xlibsx}... "
	else
		printf "Checking for ${xheaderx}... "
	fi
	ccode="#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <${xheaderx}>
int main (int argc, char **argv) { return 0; }
"
	w_compile_c_code "$ccode" "" "${xlibsx}"
	if [ $? -eq 0 ] ; then
		w_headers="$w_headers ${xheaderx}"
		echo "yes"
		xretval=0
	else
		echo "no"
		xretval=1
	fi
	return ${xretval}
}


w_check_header_and_libs_required()
{
	zzheaderzz=$1
	if [ -z "$2" ] ; then
		exit_error "w_check_header_and_libs_required: 2nd paramater <libs> is required"
	fi
	shift
	zzlibszz=$@
	w_check_header_and_libs ${zzheaderzz} ${zzlibszz}
	if [ $? -eq 0 ] ; then
		LIBS="$LIBS ${zzlibszz}"
	else
		exit_error "ERROR: ${zzheaderzz} + ${zzlibszz} is required"
	fi
}

w_check_headers()
{
	for zzheaderzz in $@
	do
		w_check_header_and_libs ${zzheaderzz}
	done
}

w_check_headers_required()
{
	for zzheaderzz in $@
	do
		w_check_header_and_libs ${zzheaderzz}
		if [ $? -ne 0 ] ; then
			exit_error "ERROR: ${zzheaderzz} is required"
		fi
	done
}


w_check_cflag()
{
	printf "Checking if $1 is supported... "
	c_code='int main (int argc, char **argv) { return 0; }'
	w_compile_c_code "$ccode" ${1}
	if [ $? -eq 0 ] ; then
		echo "yes"
		return 0
	else
		echo "no"
		return 1
	fi
}


w_check_command() # sets $wtmp_cmd
{
	printf "Checking for $1... "
	wtmp_cmd="$(check_command "$1")"
	if [ -n "$wtmp_cmd" ] ; then
		echo "$wtmp_cmd"
		return 0
	else
		echo "no"
		return 1
	fi
}

w_check_commands()
{
	for wcmdw in $@ ; do
		w_check_command ${wcmdw}
	done
}

w_check_commands_required()
{
	for wcmdw in $@ ; do
		w_check_command ${wcmdw}
		if [ $? -ne 0 ] ; then
			exit_error "ERROR: $wcmdw is required"
		fi
	done
}


w_check_command_find_first() # sets $wtmp_cmd
{
	wtmp_cmd=''
	for wcmdw in $@
	do
		w_check_command ${wcmdw}
		if [ $? -eq 0 ] ; then
			return
		fi
	done
	wtmp_cmd=''
	return 1
}


w_prefer_gnu_make() # param: require
{
	printf "Checking for GNU make... "
	if [ -n "$MAKE" ] && "$MAKE" --version 1>/dev/null 2>&1 ; then
		echo "$MAKE (environment)"
		W_GNU_MAKE="MAKE=$MAKE"
	elif make --version 1>/dev/null 2>&1 ; then
		echo "make"
		W_GNU_MAKE='MAKE=make'
	elif gmake --version 1>/dev/null 2>&1 ; then
		echo "gmake"
		W_GNU_MAKE='MAKE=gmake'
	else
		echo "no"
		if [ -n "$1" ] ; then
			exit_error "ERROR: GNU make is required"
		fi
	fi
}

w_require_gnu_make()
{
	w_prefer_gnu_make require
}

#==========================================================

#test "$CC"    || CC='gcc'
#test "$CXX"   || CXX='g++'
test "$STRIP"  || STRIP='strip'
test "$AR"     || AR='ar'
test "$AS"     || AS='as'
test "$NM"     || NM='nm'
test "$RANLIB" || RANLIB='ranlib'
test "$OBJCOPY" || OBJCOPY='objcopy'
test "$OBJDUMP" || OBJDUMP='objdump'
static_link=''
# mingw
test "$DLLTOOL" || DLLTOOL='dlltool'
test "$WINDRES" || WINDRES='windres'
test "$WINDMC"  || WINDMC='windmc'

prefix=/usr/local
exec_prefix='${prefix}'
libdir='${exec_prefix}/lib'
bindir='${exec_prefix}/bin'
sbindir='${exec_prefix}/sbin'
libexecdir='${exec_prefix}/libexec'
includedir='${prefix}/include'
datarootdir='${prefix}/share'
datadir='${datarootdir}'
localstatedir='${prefix}/var'
sysconfdir='${prefix}/etc'
docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
infodir='${datarootdir}/info'
mandir='${datarootdir}/man'
localedir='${datarootdir}/locale'
runstatedir='${localstatedir}/run'
top_builddir="$(pwd)"
top_srcdir="$(pwd)"
builddir=.
srcdir=.

print_eval_var()
{
	zzvareval=
	for i in $@ # perform up to 2 evals
	do
		zzvareval="$(eval echo $i)"
		zzvareval="$(eval echo $zzvareval)"
	done
	echo "$zzvareval"
}

#==========================================================

help()
{
	echo "
Usage: ./configure [OPTION]... [VAR=VALUE]...

To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE.  See below for descriptions of some of the useful variables.

Defaults for the options are specified in brackets.

Installation directories:
  --prefix=PREFIX         install architecture-independent files in PREFIX
                          [${prefix}]
  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
                          [${exec_prefix}]

By default, 'make install' will install all the files in
'/usr/local/bin', '/usr/local/lib' etc.  You can specify
an installation prefix other than '/usr/local' using '--prefix',
for instance '--prefix=\$HOME'.

For better control, use the options below.

Fine tuning of the installation directories:
  --bindir=DIR            user executables [${bindir}]
  --sbindir=DIR           system admin executables [${sbindir}]
  --libexecdir=DIR        program executables [${libexecdir}]
  --sysconfdir=DIR        read-only single-machine data [${sysconfdir}]
  --localstatedir=DIR     modifiable single-machine data [${localstatedir}]
  --runstatedir=DIR       modifiable per-process data [${runstatedir}]
  --libdir=DIR            object code libraries [${libdir}]
  --includedir=DIR        C header files [${includedir}]
  --datarootdir=DIR       read-only arch.-independent data root [${datarootdir}]
  --datadir=DIR           read-only architecture-independent data [${datadir}]
  --infodir=DIR           info documentation [${infodir}]
  --localedir=DIR         locale-dependent data [${localedir}]
  --mandir=DIR            man documentation [${mandir}]
  --docdir=DIR            documentation root [${docdir}]

Optional Features:
  (Use --disable-FEATURE or --enable-FEATURE)
$(print_optional_features)
Optional Packages:
  (Use --without-PACKAGE or --with-PACKAGE[=ARG] )
  --with-sysroot[=DIR]    Set DIR as the compiler's sysroot directory
                          for headers and libraries
$(print_optional_packages)
Some influential environment variables:
  CC          C compiler command
  CFLAGS      C compiler flags
  CXXFLAGS    C++ compiler flags
  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
              nonstandard directory <lib dir>
  LIBS        libraries to pass to the linker, e.g. -l<library>
  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
              you have headers in a nonstandard directory <include dir>
  PKG_CONFIG  path to pkg-config utility
  PKG_CONFIG_PATH
              directories to add to pkg-config's search path
  PKG_CONFIG_LIBDIR
              path overriding pkg-config's built-in search path
$(print_extra_env_variables)

Use these variables to override the choices made by 'configure' or to help
it to find libraries and programs with nonstandard names/locations.
"
	exit
}

#==========================================================

print_optional_features()
{
	for confx in ${w_opts_configure} ${extra_configure_opts}
	do
		opt_print_${confx}
	done
	test -n "${extra_configure_opts}" || \
	test -n "${w_opts_configure}" && printf "  \n"
}

print_optional_packages()
{
	for confx in ${extra_packages_opts}
	do
		opt_pkg_print_${confx}
	done
	printf "  \n"
}

print_extra_env_variables()
{
	for evar in ${extra_env_vars}
	do
		echo "  ${evar}_CFLAGS  compiler flags for ${evar}, overriding pkg-config"
		echo "  ${evar}_LIBS    linker flags for ${evar}, overriding pkg-config"
	done
}

#==========================================================

getvalue() {
	echo $1 | cut -f 2 -d '='
}

for i in $@
do
	case $i in
		--host=*) host="$(getvalue $i)" ;;
		CFLAGS=*)   CFLAGS="$CFLAGS $(getvalue $i)"     ;;
		CPPFLAGS=*) CPPFLAGS="$CPPFLAGS $(getvalue $i)" ;;
		LDFLAGS=*)  LDFLAGS="$LDFLAGS $(getvalue $i)"   ;;
		LXXFLAGS=*) LXXFLAGS="$LXXFLAGS $(getvalue $i)"   ;;
		CXXFLAGS=*) CXXFLAGS="$CXXFLAGS $(getvalue $i)"   ;;
		LIBS=*)  LIBS="$LIBS $(getvalue $i)"   ;;
		CC=*)    CC="$(getvalue $i)"     ;;
		CXX=*)   CXX="$(getvalue $i)"    ;;
		STRIP=*) STRIP="$(getvalue $i)"  ;;
		AR=*)    AR="$(getvalue $i)"     ;;
		AS=*)    AS="$(getvalue $i)"     ;;
		NM=*)    NM="$(getvalue $i)"     ;;
		DLLTOOL=*) DLLTOOL="$(getvalue $i)" ;;
		WINDRES=*) WINDRES="$(getvalue $i)" ;;
		WINDMC=*)  WINDMC="$(getvalue $i)" ;;

		--prefix=*)     prefix="$(getvalue $i)"     ;;
		--exec_prefix=*) exec_prefix="$(getvalue $i)"     ;;
		--libdir=*)     libdir="$(getvalue $i)"     ;;
		--bindir=*)     bindir="$(getvalue $i)"     ;;
		--sbindir=*)    sbindir="$(getvalue $i)"    ;;
		--libexecdir=*) libexecdir="$(getvalue $i)" ;;
		--includedir=*) includedi="$(getvalue $i)"  ;;
		--datarootdir=*)   datarootdir="$(getvalue $i)"   ;;
		--datadir=*)    datadir="$(getvalue $i)"          ;;
		--localstatedir=*) localstatedir="$(getvalue $i)" ;;
		--sysconfdir=*)    sysconfdir="$(getvalue $i)"    ;;
		--docdir=*)    docdir="$(getvalue $i)"   ;;
		--infodir=*)   infodir="$(getvalue $i)"  ;;
		--mandir=*)    mandir="$(getvalue $i)"   ;;
		--localedir=*)   localedir="$(getvalue $i)"   ;;
		--runstatedir=*) runstatedir="$(getvalue $i)" ;;
		--with-sysroot=*) sysroot="$(getvalue $i)" ;;
		--with-sysroot) sysroot='-print-sysroot' ;;
		--without-sysroot) sysroot='' ;;
		--enable-static-link)  static_link=1 ;;
		--disable-static-link) static_link=  ;;

		---*) exit_error "Invalid opt: $i" ;;
		-h|--help) help ;;
	esac
done

if [ -n "$W_PKG_CONFIG_STATIC" ] ; then
	static_link=1
fi

for confx in ${w_opts_configure} ${extra_configure_opts} ${extra_packages_opts}
do
	opt_configure_${confx} "$@"
done

# ====================================================

echo
set_cc
set_cxx
set_w_pkg_config

OS_BUILD=$(uname -s)
OS_CROSS=''
OS_TARGET=''

if test -n "$host" ; then
	printf "Checking cross-compiler... "
	CROSS_IS_FULL_PATH=''
	CROSS_BASE_DIR=''
	OS_CROSS="$host"
	case $host in /*)
		CROSS_IS_FULL_PATH=1
		CROSS_BASE_DIR="$(dirname $host)/"
		OS_CROSS="$(basename $host)"
		;;
	esac
	cross_base_dir=''
	w_c_cross_ok=$(check_command ${host}-cc ${host}-gcc ${host}-clang)
	w_cpp_cross_ok=
	if [ -n "$w_c_cross_ok" ] ; then
		CC="$w_c_cross_ok";
	fi
	#--
	if [ "$PROJECT_TYPE" = "C++" ] ; then
		w_cpp_cross_ok=$(check_command ${host}-c++ ${host}-g++ ${host}-clang++)
		if [ "$w_cpp_cross_ok" ] ; then
			CXX="$w_cpp_cross_ok";
		fi
	else
		w_cpp_cross_ok=1
		CXX=${CROSS_BASE_DIR}${host}-c++
	fi
	#--
	if [ -n "$w_c_cross_ok" ] && [ -n "$w_cpp_cross_ok" ]; then
		LD=${CROSS_BASE_DIR}${host}-${LD}
		STRIP=${CROSS_BASE_DIR}${host}-${STRIP}
		AR=${CROSS_BASE_DIR}${host}-${AR}
		AS=${CROSS_BASE_DIR}${host}-${AS}
		NM=${CROSS_BASE_DIR}${host}-${NM}
		RANLIB=${CROSS_BASE_DIR}${host}-${RANLIB}
		OBJCOPY=${CROSS_BASE_DIR}${host}-${OBJCOPY}
		OBJDUMP=${CROSS_BASE_DIR}${host}-${OBJDUMP}
		#--
		DLLTOOL=${CROSS_BASE_DIR}${host}-${DLLTOOL}
		WINDRES=${CROSS_BASE_DIR}${host}-${WINDRES}
		WINDMC=${CROSS_BASE_DIR}${host}-${WINDMC}
		#--
		echo "$host"
	else
		exit_error "not found"
	fi
	if [ -z "$CROSS_IS_FULL_PATH" ] ; then
		# cross compiler is not a full path
		CC="$(basename $CC)"
		if [ -n "$CXX" ] ; then
			CXX="$(basename $CXX)"
		fi
	fi
fi

if [ -n "$static_link" ] ; then
	CC="$CC -static"
	CXX="$CXX -static"
fi

if [ -n "${sysroot}" ] ; then
	if [ "${sysroot}" = "-print-sysroot" ] ; then
		sysroot="$($CC -print-sysroot)"
		if [ -z "$sysroot" ] ; then
			exit_error "--with-sysroot ERROR: compiler doesn't support -print-sysroot"
		fi
	fi
	if ! [ -d "$sysroot" ] ; then
		exit_error "--with-sysroot ERROR: $sysroot is not a directory"
	fi
	CC="$CC --sysroot=${sysroot}"
	CXX="$CXX --sysroot=${sysroot}"
	if [ -n "$W_SYSROOT_EXTRA" ] ; then
		if [ -d ${sysroot}/include ] ; then
			CFLAGS="-I${sysroot}/include $CFLAGS"
			CXXFLAGS="-I${sysroot}/include $CXXFLAGS"
		fi
		if [ -d ${sysroot}/lib ] ; then
			LDFLAGS="-L${sysroot}/lib $LDFLAGS"
			LXXFLAGS="-L${sysroot}/lib $LXXFLAGS"
		fi
	fi
fi

#==========================================================

case ${OS_BUILD} in
	CYGWIN*) OS_BUILD="Cygwin" ;;
	MINGW*)  OS_BUILD="MinGW"  ;;
	MSYS*)   OS_BUILD="MinGW"  ;;
esac

OS_TARGET=${OS_BUILD}

if [ -n "$OS_CROSS" ] ; then
	# cross-compiling, reset OS_TARGET
	OS_TARGET=''
	# determine OS_TARGET again
	case $OS_CROSS in
		*-mingw*)   OS_TARGET='MinGW'   ;;
		*-darwin*)  OS_TARGET='Darwin'  ;;
		*-linux-*)  OS_TARGET='Linux'   ;;
		*-freebsd*) OS_TARGET='FreeBSD' ;;
	esac
fi

case $OS_TARGET in
	Linux)   SYSDEFINE='__linux__=1' ;;
	MinGW)   SYSDEFINE='__MINGW32__=1' ;;
	FreeBSD) SYSDEFINE='__FreeBSD__=1' ;;
	Darwub)  SYSDEFINE='__APPLE__=1' ;;
esac

TARGET_OS="$OS_TARGET"

#==========================================================

CFLAGS="$CFLAGS $PROJECT_CFLAGS"
CPPFLAGS="$CPPFLAGS $PROJECT_CPPFLAGS"
CXXFLAGS="$CXXFLAGS $PROJECT_CXXFLAGS"
LDFLAGS="$LDFLAGS $PROJECT_LDFLAGS"
LXXFLAGS="$LXXFLAGS $PROJECT_LXXFLAGS"
LIBS="$LIBS $PROJECT_LIBS"

#==========================================================

echo > config.log
case $PROJECT_TYPE in
	C)   WCVERW=$($CC --version 2>>config.log)  ;;
	C++) WCVERW=$($CXX --version 2>>config.log) ;;
esac
echo "$WCVERW" >> config.log
if [ -n "$(echo "$WCVERW" | grep "Free Software Foundation")" ] ; then
	printf "\n- GCC has been detected\n" >>config.log
	GCC='yes'
fi

w_headers=''
#----------
w_main_func # main function where the user performs all sorts of tasks
#----------
# apps to check, see configure.project (XXX_CFLAGS, XXX_LIBS)
for appx in ${w_opts_check} ${apps_to_check}
do
	opt_check_${appx}
done
# custom checks
for xcheckx in ${w_opts_after_check} ${w_custom_checks}
do
	${xcheckx}
done

#==========================================================
#                  config.mk
#==========================================================

# ensure -DHAVE_CONFIG_H
CFLAGS="-DHAVE_CONFIG_H $CFLAGS "
CXXFLAGS="-DHAVE_CONFIG_H $CXXFLAGS"

cat > config.mk <<EOF
# generated by ./configure
${W_GNU_MAKE}

prefix = ${prefix}
exec_prefix = ${exec_prefix}
libdir = ${libdir}
bindir = ${bindir}
sbindir = ${sbindir}
libexecdir = ${libexecdir}
includedir = ${includedir}
datarootdir = ${datarootdir}
datadir = ${datadir}
localstatedir = ${localstatedir}
sysconfdir = ${sysconfdir}
docdir = ${docdir}
infodir = ${infodir}
mandir = ${mandir}
localedir = ${localedir}
runstatedir = ${runstatedir}
top_builddir = ${top_builddir}
top_srcdir = ${top_srcdir}
builddir = ${builddir}
srcdir = ${srcdir}

#=================================================

INSTALL = install -c
INSTALL_DATA = install -c -m 644

PACKAGE = ${PACKAGE}
VERSION = ${VERSION}
PACKAGE_URL = ${PACKAGE_URL}
PACKAGE_NAME = ${PACKAGE_NAME}
PACKAGE_STRING = ${PACKAGE_STRING}
PACKAGE_TARNAME = ${PACKAGE_TARNAME}
PACKAGE_BUGREPORT = ${PACKAGE_BUGREPORT}
PACKAGE_VERSION = ${PACKAGE_VERSION}

OS_BUILD = ${OS_BUILD}
OS_CROSS = ${OS_CROSS}
OS_TARGET = ${OS_TARGET}
TARGET_OS = ${TARGET_OS}

#=================================================

CC = ${CC}
CXX = ${CXX}
STRIP = ${STRIP}
AR = ${AR}
AS = ${AS}
NM = ${NM}
RANLIB = ${RANLIB}
OBJCOPY = ${OBJCOPY}
OBJDUMP = ${OBJDUMP}

DLLTOOL = ${DLLTOOL}
WINDRES = ${WINDRES}
WINDMC = ${WINDMC}

CFLAGS = ${CFLAGS}
CPPFLAGS = ${CPPFLAGS}
CXXFLAGS = ${CXXFLAGS}
LXXFLAGS = ${LXXFLAGS}
LDFLAGS = ${LDFLAGS}
LIBS = ${LIBS}

#=================================================

${SYSDEFINE}
${make_extra_flags}
${w_config_mk_extra_lines}
EOF

#==========================================================
#                  config.sh (=config.mk)
#==========================================================

cat > config.sh <<EOF
#generated by ./configure

prefix="${prefix}"
exec_prefix="${exec_prefix}"
libdir="${libdir}"
bindir="${bindir}"
sbindir="${sbindir}"
libexecdir="${libexecdir}"
includedir="${includedir}"
datarootdir="${datarootdir}"
datadir="${datadir}"
localstatedir="${localstatedir}"
sysconfdir="${sysconfdir}"
docdir="${docdir}"
infodir="${infodir}"
mandir="${mandir}"
localedir="${localedir}"
runstatedir="${runstatedir}"
top_builddir="${top_builddir}"
top_srcdir="${top_srcdir}"
builddir="${builddir}"
srcdir="${srcdir}"

#=================================================

INSTALL="install -c"
INSTALL_DATA="install -c -m 644"

PACKAGE="${PACKAGE}"
VERSION="${VERSION}"
PACKAGE_URL="${PACKAGE_URL}"
PACKAGE_NAME="${PACKAGE_NAME}"
PACKAGE_STRING="${PACKAGE_STRING}"
PACKAGE_TARNAME="${PACKAGE_TARNAME}"
PACKAGE_BUGREPORT="${PACKAGE_BUGREPORT}"
PACKAGE_VERSION="${PACKAGE_VERSION}"

OS_BUILD="${OS_BUILD}"
OS_CROSS="${OS_CROSS}"
OS_TARGET="${OS_TARGET}"
TARGET_OS="${TARGET_OS}"

#=================================================

CC="${CC}"
CXX="${CXX}"
STRIP="${STRIP}"
AR="${AR}"
AS="${AS}"
NM="${NM}"
RANLIB="${RANLIB}"
OBJCOPY="${OBJCOPY}"
OBJDUMP="${OBJDUMP}"

DLLTOOL="${DLLTOOL}"
WINDRES="${WINDRES}"
WINDMC="${WINDMC}"

CFLAGS="${CFLAGS}"
CPPFLAGS="${CPPFLAGS}"
CXXFLAGS="${CXXFLAGS}"
LXXFLAGS="${LXXFLAGS}"
LDFLAGS="${LDFLAGS}"
LIBS="${LIBS}"

#=================================================

${SYSDEFINE}
${config_sh_extra}
EOF

if [ -n "${config_mk_flags}" ] ; then
	for env in ${config_mk_flags}
	do
		echo "${env}_CFLAGS = $(eval echo \$${env}_CFLAGS)
${env}_LIBS  = $(eval echo \$${env}_LIBS)" >> config.mk
		#--
		echo "${env}_CFLAGS=\"$(eval echo \$${env}_CFLAGS)\"
${env}_LIBS=\"$(eval echo \$${env}_LIBS)\"" >> config.sh
    done
fi


#==========================================================
#                  Makefiles.in
#==========================================================

if [ -n "$W_MAKEFILES_IN" ] ; then
	w_makefiles=$(find . -name Makefile.in | sed -e 's%\.in%%')
	for makefile in ${w_makefiles}
	do
		cat config.mk ${makefile}.in > ${makefile}
	done
fi

#==========================================================

. ./config.sh

#==========================================================
#                       config.h
#==========================================================

cat > config.h <<EOF
/* generated by ./configure */
#ifndef __W_CONFIGURE_CONFIG_H__
#define __W_CONFIGURE_CONFIG_H__

#define PACKAGE "${PACKAGE}"
#define VERSION "${VERSION}"
#define PACKAGE_URL "${PACKAGE_URL}"
#define PACKAGE_NAME "${PACKAGE_NAME}"
#define PACKAGE_STRING "${PACKAGE_STRING}"
#define PACKAGE_TARNAME "${PACKAGE_TARNAME}"
#define PACKAGE_BUGREPORT "${PACKAGE_BUGREPORT}"
#define PACKAGE_VERSION "${PACKAGE_VERSION}"

// use PACKAGE_* (i.e: DATADIR may break a MinGW build)
#define PACKAGE_PREFIX "$prefix"
#define PACKAGE_LOCALEDIR "$localedir"
#define PACKAGE_DATADIR "$datadir"
#define PACKAGE_SYSCONFDIR "$sysconfdir"
#define PACKAGE_DOCDIR "$docdir"
#define PACKAGE_MANDIR "$mandir"

#define OS_TARGET "${OS_TARGET}"
${config_h_extra}
EOF

if [ -n "${w_headers}" ] ; then
	(
		for xheader in ${w_headers}
		do
			zheader=$(echo "$xheader" | tr '/' '_' | tr '.' '_' | tr '[:lower:]' '[:upper:]')
			echo "#define HAVE_${zheader} 1"
		done
	) >> config.h
fi

if [ -n "${config_h_have}" ] ; then
	(
		for feat in ${config_h_have}
		do
			echo "#define HAVE_${feat} 1"
		done
	) >> config.h
fi

#==========================================================

for infile in ${w_infiles}
do
	./w_conf/00_standard_infile.sh ${infile}
done

#==========================================================

w_finish_func

echo "${w_config_h_extra_lines}
#endif /* __W_CONFIGURE_CONFIG_H__ */" >> config.h

#==========================================================

echo
echo "* Now run 'make'  (or 'make clean' first if the app is already compiled)"
echo
