#! /bin/sh
#
# buildconf - regenerate configure script from macros.
# Usage: ./buildconf "/path/to/autotools"
#
# aclocal
# libtoolize --force --copy
# autoheader
# automake --foreign --copy --add-missing
# autoconf
#

# Determine if Autoconf tools are the correct version, needed to re-generate configure
AC_VER=`head ./configure | grep -i autoconf | sed -e 's/.*toconf //' -e 's/ .*//' -e 's/\.$//'`
AM_VER=`head ./Makefile.in | grep -i automake | sed -e 's/.*tomake //' -e 's/ .*//' -e 's/\.$//'`
LT_VER=`head -50 ./ltmain.sh | grep "VERSION=" | sed -e 's/^VERSION=//'`

deps="autoconf-$AC_VER automake-$AM_VER libtoolize-$LT_VER"

AT_PATH="$1"
if [ ! "$AT_PATH" ]; then AT_PATH="$PWD/autotools"; fi
if [ ! -d "$AT_PATH" ]; then ./generate-autotools; fi

if [ ! "`basename $AT_PATH`" = "bin" ]; then AT_PATH="$AT_PATH/bin"; fi

if [ ! "$AT_PATH" ]; then
	printf "Buildconf requires autoconf, automake and libtool. See autoconf.markdown for details.\n"
	printf "Usage: ./buildconf \"/path/to/autotools\".\n"
	exit 1
fi

for prg_ver in $deps; do
	prg=`echo "$prg_ver" | sed -e 's/-.*$//'`
	if [ ! -x "$AT_PATH/$prg" ]; then
		printf "Error: $prg not found. Searched for executable '$prg' in $AT_PATH.\n"
		exit 1
	fi
	ver=`echo "$prg_ver" | sed -e 's/^.*-//'`
	INSTALLED_VER=`$AT_PATH/$prg --version | grep -i $prg | sed -e 's/.* //'`
	if [ ! "$INSTALLED_VER" = "$ver" ]; then
		printf "Error: Autoconf version mismatch. Buildconf requires $prg version $ver.\n"
		printf "You have $prg version $INSTALLED_VER. See autoconf.markdown for details.\n"
		exit 1
	fi
done

# Use the same versions of autotools, installed in autotools path
PATH=$AT_PATH:$PATH

# Checks passed, regenerate ./configure and associcated files
aclocal
libtoolize --force --copy
autoheader
automake --foreign --copy --add-missing
autoconf
rm -f fpm_autoconfig.h.in~

# # Alternative method (and without --foreign)
# touch NEWS README AUTHORS ChangeLog
# PATH=$(pwd)/autotools/bin:$PATH autoreconf -ivf
