#! /bin/sh

# checking for the GLOBUS_LOCATION


if test "x$GLOBUS_LOCATION" = "x"; then
    echo "Using default globus location of /usr"
    GLOBUS_LOCATION=/usr
fi

error()
{
    echo ""
    echo "ERROR: bootstrap failed!"
    echo ""
    exit 1
}


# check for autotools

for program in automake aclocal autoconf autoheader
    do
    ($program --version ) > /dev/null 2>&1 || { 
    echo "ERROR: $program not found" >&2
    exit 1
    }
done

config=

# local macros
config="$config -I ./config"

# macros we install
config="$config -I ./aclocal"

GPT_LOCATION="${GPT_LOCATION:-${GLOBUS_LOCATION:-/usr}}"
# test to see if GPT macros are in a seperate location
if test ! -f "$GLOBUS_LOCATION/share/gpt_autoconf_macros.m4"; then
    if test "x$GPT_LOCATION" = "x"; then
        echo "ERROR Globus Packaging Tools not found" >&2
        echo "ERROR either set GPT_LOCATION or install them in $GLOBUS_LOCATION" >&2
        exit 1
    elif test -f "$GPT_LOCATION/share/globus/globus_aclocal/gpt_autoconf_macros.m4";  then
	config="$config -I $GPT_LOCATION/share/globus/globus_aclocal"
    elif test -f "$GPT_LOCATION/share/globus/aclocal/gpt_autoconf_macros.m4"; then
        config="$config -I $GPT_LOCATION/share/globus/aclocal"
    else
	echo "ERROR Can't find gpt_autoconf_macros.m4" 1>&2
	exit 1
    fi
else
    config="$config -I $GLOBUS_LOCATION/share/globus_aclocal"
fi

if test "x$GPT_LOCATION" = "x"; then
    GPT_LOCATION=$GLOBUS_LOCATION
fi

$GPT_LOCATION/sbin/gpt_extract_data \
    --name --version --build_env ./pkgdata/pkg_data_src.gpt.in > gptdata.sh

echo "running gpt-to-pkgconfig"
$GPT_LOCATION/sbin/gpt-to-pkgconfig ./pkgdata/pkg_data_src.gpt.in

echo "running aclocal $config"
aclocal $config || error

if test -f acconfig.h ; then
echo "running autoheader"
    autoheader || error
fi

OLDIFS="$IFS"
IFS="
"
for x in `echo "${PATH}" | tr ":" "\n"`; do
    if test -x "$x/libtoolize"; then
        libtoolize=libtoolize
        break
    elif test -x "$x/glibtoolize"; then
        libtoolize=glibtoolize
        break
    fi
done
IFS="$OLDIFS"

echo "running $libtoolize --copy --force"
$libtoolize --copy --force || \
  $libtoolize --copy --force || error

echo "running automake --copy -add-missing --force-missing --foreign"
automake --copy --add-missing --force-missing --foreign || \
  automake --copy --add-missing --force-missing --foreign || error


echo "running gpt_create_automake_rules"
$GPT_LOCATION/sbin/gpt_create_automake_rules || error


echo "running autoconf"
autoconf || error


# update stamp.h.in

if test -f "stamp-h.in" ; then
    touch stamp-h.in
fi
