#! /bin/sh

# Make sure we do not export SHELLOPTS to child processes. Otherwise, they
# would inherit the "set -e" below, and those scripts expect to continue on
# "errors". We could do "export -n SHELLOPTS", but we don't want to run
# configure with SHELLOPTS=igncr, as is often done in Cygwin, because some
# versions of autoconf put a hard CR in configure, and igncr ignores that CR.
# Better to give an error here.
if (export | grep -i shellopts > /dev/null); then
  echo error: SHELLOPTS environment variable must not be exported
  echo SHELLOPTS = $SHELLOPTS
  exit 1
fi

DISTRIBUTION_MODE=false

# Find a version of awk that supports gsub
NAWK=`which nawk 2> /dev/null`
if [ -x "${NAWK}" ]; then
  : nawk found
else
  NAWK=awk
fi

set -e # Stop on errors.

# The -w switch is used when creating the source distribution from the contents
# of the repository. Its purpose is to adapt configure.ac for files that are
# present in the repository but missing from source packages, and also to tweak
# some knobs that are intended to differ between the repository and the source
# package.
usage() {
  echo "$0 [-w]"
  echo "  -w  distribution mode: adjust MANIFEST and generate configure"
  echo "      for packaged sources (not for building directly from checkout)"
  exit 1
}

while getopts w opt
do
  case "$opt" in
    w)
      DISTRIBUTION_MODE=true
      ;;
    *)
      usage
      ,,
  esac
done

if [ -f support/distrib.m4 ]; then
  echo "Using source distribution data from support/distrib.m4"
fi

rm -f aclocal.m4 support/libtool.m4 configure

echo "Libtoolizing"
# If libtoolize advises us to get a particular version of libtool.m4,
# copy it locally.
libtool_m4=`libtoolize --copy --force | sed -n -e '/You should add the contents of \`\([^'\'']*\)'\''.*$/s//\1/p'`
if [ -n "$libtool_m4" ]; then
  cp $libtool_m4 support/libtool.m4
else
  touch support/libtool.m4
fi

mv support/ltmain.sh support/ltmain.sh.orig
sed -e '/xlinker)/,/;;$/s/\$wl/-Xlinker /g' < support/ltmain.sh.orig > support/ltmain.sh
rm -f support/ltmain.sh.orig

show_step() {
  echo "Running `$1 --version | head -1`"
}

show_step aclocal
aclocal -I support

show_step autoheader
autoheader

show_step autoconf
autoconf

show_step automake
automake --add-missing --copy

echo "Generating IDL tree accessors"
(cd compilers/idlac && python make_nodes.py nodes.txt > nodes.ada \
 && gnatchop -w nodes.ada && rm -f nodes.ada)

echo "Doing the necessary date modifications"
for f in \
  configure.ac	\
  aclocal.m4	\
  Makefile.in	\
  configure	\
  stamp-h.in	\
  config.h.in
do
  find . -name $f | grep -v '^\./Makefile.in$' | while read ff
  # The above 'grep' is to avoid touching the Makefile.in in the root
  # directory, since that's now a source file, rather than being generated from
  # Makefile.am.
  do
    touch $ff
  done
  sleep 1
done
