#!/bin/sh
#
# This file is distributed under the terms of the MIT License.
# See the LICENSE file at the top of this tree, or if it is missing a copy can
# be found at http://opensource.org/licenses/MIT
#
# Make everything

dir=$(dirname $0)
cd "${dir}"

MAKE=make
which gmake >/dev/null 2>&1 && MAKE=gmake
export MAKE
export LD_LIBRARY_PATH=
#MAKE_PARALLEL=-j4  # TODO: make this depend on if it's in CI

do_bootstrap=

if [ -f configure ]; then
	# Find if any autotools input is newer than configure
	if find . -type f '(' -name 'Makefile.*' -or -name 'configure.*' -or -name '*.in' ')' -newer configure | grep -q "."; then
		echo "- autotools out of date; bootstrap required"
		do_bootstrap=y
	fi

	# Find if any autotools output file is missing
	outputs=$(eval $(grep ^ac_config_files= configure); echo $ac_config_files)
	for i in ${outputs}; do
		if [ ! -f "$i" ]; then
			echo "- '$i' is missing; bootstrap required"
			do_bootstrap=y
		fi
	done
else
	echo "- 'configure' is missing; bootstrap required"
	do_bootstrap=y
fi

if [ "${do_bootstrap}" ]; then
	[ -f Makefile ] && $MAKE $MAKE_PARALLEL clean
	./bootstrap
	./do-configure-debug
	$MAKE $MAKE_PARALLEL clean
fi

exec $MAKE $MAKE_PARALLEL
