#! /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

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

show_step aclocal
aclocal -I support

show_step autoheader
autoheader

show_step autoconf
autoconf

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	\
  configure	\
  stamp-h.in	\
  config.h.in
do
  find . -name $f | while read ff; do
    touch $ff
  done
  sleep 1
done
