#! /bin/sh

reconfigure()
{
    for f in `find . -name '*.in'`; do
	BASE=`echo $f | sed 's/.in$//'`
	sh config.status < $f > $BASE
	chmod --reference=$f $BASE
    done
}

if [ x"$1" = "x--reconfigure" ]; then
    reconfigure
    exit
fi

BINDIR=/usr/local/bin
LIBDIR=/usr/local/lib/ccontrol
MANDIR=/usr/local/share/man
XMLTO=`which xmlto`
ASCIIDOC=`which asciidoc`
OPTFLAGS=-O3
VALGRIND=`which valgrind`
VERSION=0.9.1
VERSION_NAME="Michael Neuling"
while [ $# -gt 0 ]; do
    case "$1" in
	--bindir=*) BINDIR=`echo $1 | cut -d= -f2-`;;
	--libdir=*) LIBDIR=`echo $1 | cut -d= -f2-`;;
	--mandir=*) MANDIR=`echo $1 | cut -d= -f2-`;;
	--xmlto=*) XMLTO=`echo $1 | cut -d= -f2-`;;
	--asciidoc=*) ASCIIDOC=`echo $1 | cut -d= -f2-`;;
	--enable-debug) OPTFLAGS=-g; DEBUG=1; NODIET=1;;
	--disable-dietlibc) NODIET=1;;
	--disable-valgrind) VALGRIND="";;
	*)
	    echo "Usage: configure [<options>]" >&2
	    echo "Valid options, with defaults:">&2
	    echo "  --bindir=$BINDIR" >&2
	    echo "  --libdir=$LIBDIR" >&2
	    echo "  --mandir=$MANDIR" >&2
	    echo "  --xmlto=$XMLTO" >&2
	    echo "  --asciidoc=$ASCIIDOC" >&2
	    echo "  --enable-debug" >&2
	    echo "  --disable-dietlibc" >&2
	    echo "  --disable-valgrind" >&2
	    exit 1
	    ;;
    esac
    shift
done

CC=${CC:-gcc}
if [ -z "$NODIET" ]; then
    echo -n Looking for dietlibc...
    if type diet >/dev/null 2>&1; then
	echo yes
	CC="diet $CC"
    else
	echo no
    fi
fi
echo -n Looking for compiler...
echo $CC

echo -n Looking for compiler flags...
CFLAGS="${CFLAGS:--Wall -Wmissing-declarations} $OPTFLAGS"
echo $CFLAGS

echo -n Looking for xmlto...
if [ -z "$XMLTO" ]; then
    echo not found '(no regenerating man pages for you)'
    XMLTO="@echo No xmlto found; exit 0; :"
else
    echo $XMLTO
fi

echo -n Looking for asciidoc...
if [ -z "$ASCIIDOC" ]; then
    echo not found '(no regenerating man pages for you)'
    ASCIIDOC="@echo No asciidoc found; exit 0; :"
else
    echo $ASCIIDOC
fi

DEBVERSION=`head -n1 debian/changelog | sed -e 's/^ccontrol (\([0-9.]\+\)-[0-9]\+) .*$/\1/'`

if [ "$DEBVERSION" != "$VERSION" ]; then
       echo "Fixing up debian/changelog as the version was changed."
       # FIXME: -R is GNU date specific
       DATE=`date -R`
       cp debian/changelog debian/changelog.old
       (sed -e "s/@VERSION@/$VERSION/" -e "s/@DATE@/$DATE/" debian/changelog.template.in ; cat debian/changelog.old) > debian/changelog
       rm debian/changelog.old
fi

echo sed -e \""s,@CC@,$CC,g\"" \
	-e \""s,@BINDIR@,$BINDIR,g\"" \
	-e \""s,@LIBDIR@,$LIBDIR,g\"" \
	-e \""s,@MANDIR@,$MANDIR,g\"" \
	-e \""s,@XMLTO@,$XMLTO,g\"" \
	-e \""s,@ASCIIDOC@,$ASCIIDOC,g\"" \
	-e \""s,@CFLAGS@,$CFLAGS,g\"" \
	-e \""s,@VERSION@,$VERSION,g\"" \
	-e \""s,@VERSION_NAME@,$VERSION_NAME,g\"" \
	-e \""s,@VALGRIND@,$VALGRIND,g\"" > config.status

reconfigure
echo Configuration complete.  Type \"make\" to build.
