#!/bin/sh

# Check for proper versions of autotools
# We require:
#  - autoconf 2.50+
#  - automake 1.7+, 1.9+ for make dist
#  - libtool 1.4+

# Touch revision.m4
if [ -f ./update_revision.sh ]; then
	./update_revision.sh;
elif [ ! -f ./revision.m4 ]; then
	echo "m4_define([SVN_REV], 0)" > ./revision.m4;
	echo "m4_define([SVN_REVISION], trunk-r0)" >> ./revision.m4;
	echo "m4_define([SVN_DATE], )" >> ./revision.m4;
fi

# create m4 directory or we break older systems like RedHat/CentOS 5
mkdir -p m4

# Deal with some gentoo-specific issues
WANT_AUTOMAKE='1.9 1.8 1.7' #latest of these is chosen or default if none hits
export WANT_AUTOMAKE
WANT_AUTOCONF='2.5'
export WANT_AUTOCONF

# Default program names
test -z "$AUTOCONF" && AUTOCONF=autoconf
test -z "$AUTOHEADER" && AUTOHEADER=autoheader

test -z "$AUTOMAKE" && AUTOMAKE=automake
test -z "$ACLOCAL" && ACLOCAL=aclocal

test -z "$LIBTOOL" && for LIBTOOL in glibtool libtool; do
  ($LIBTOOL --version) < /dev/null > /dev/null 2>&1 && break
done
test -z "$LIBTOOLIZE" && for LIBTOOLIZE in glibtoolize libtoolize; do
  ($LIBTOOLIZE --version) < /dev/null > /dev/null 2>&1 && break
done

## Using prereq in autoconf rather than here, mostly for the debian systems at
## this point
if test -n "`$AUTOCONF --version 2>&1|head -n 1|egrep '1\.[0-9]+|2\.[0-4]+'`"; then
	echo "Autoconf 2.50 or above is required. Aborting build...";
	exit 1;
fi

if test -n "`$AUTOMAKE --version 2>&1|head -n 1|egrep '\<1\.[0-6](\.[0-9]+)?\>'`"; then
	echo "Automake 1.7 or above is required. Aborting build...";
	exit 1;
fi

if test -n "`$AUTOMAKE --version 2>&1|head -n 1|egrep '\<1\.7(\.[0-9]+)?|\<1\.8(\.[0-9]+)?'`"; then
	echo "make dist only supported with automake 1.9 or above" >&2;
fi

if test -n "`$LIBTOOL --version 2>&1|head -n 1|cut -f 4 -d ' '|egrep '1\.[0-3](\.[0-9]+)?$'`"; then
	echo "Libtool 1.4 or above is required. Aborting build...";
	exit 1;
fi

# clean up files which cause confusion when switch versions of auto*
rm -rf autom4te.cache

# Fire up autotools
$LIBTOOLIZE --force --copy && \
	$ACLOCAL $ACLOCAL_FLAGS && \
	$AUTOHEADER && \
	$AUTOMAKE --include-deps --add-missing --foreign --copy && \
	$AUTOCONF 
