#!/bin/sh

if [ ! -d sbin ]; then
  echo "$0 must be called from top directory (../$0)"
  exit 1
fi

# update POTFILES.in

echo "Generating po/POTFILES.in"
ls preprocessor/*/*.c src/*/*.c* | grep -v user_examples > po/POTFILES.in

# Remove unversioned files added by previous bootstrap

for f in `ls ./build-aux` ; do
  case $f in
    *.py | catalyst | *.makefile) ;;
    *) rm -rf $d/build-aux/*$ ;;
  esac
done

for d in . libple
do
  rm -rf $d/m4/codeset.m4 $d/m4/fcntl-o.m4 $d/m4/gettext.m4 \
         $d/m4/glibc2.m4 $d/m4/glibc21.m4 $d/m4/iconv.m4 $d/m4/intdiv0.m4 \
         $d/m4/intl.m4 $d/m4/intldir.m4 $d/m4/intlmacosx.m4 $d/m4/intmax.m4 \
         $d/m4/inttypes-pri.m4 $d/m4/inttypes_h.m4 $d/m4/lcmessage.m4 \
         $d/m4/lock.m4 $d/m4/longlong.m4 $d/m4/lib-ld.m4 $d/m4/lib-link.m4 \
         $d/m4/lib-prefix.m4 $d/m4/libtool.m4 $d/m4/lt~obsolete.m4 \
         $d/m4/ltoptions.m4 $d/m4/ltsugar.m4 $d/m4/ltversion.m4 $d/m4/nls.m4 \
         $d/m4/printf-posix.m4 $d/m4/po.m4 $d/m4/progtest.m4 $d/m4/size_max.m4 \
         $d/m4/stdint_h.m4 $d/m4/threadlib.m4 $d/m4/uintmax_t.m4 $d/m4/visibility.m4 \
         $d/m4/wchar_t.m4 $d/m4/wint_t.m4 $d/m4/xsize.m4
done

# Simply run autoreconf.

# If only gettext 0.17 is available, allow it by modifying configure.ac temporarily,
# but otherwise prefer 0.18.

cs_gettext_version=`gettext --version | head -1 | sed -e s/gettext.*0/0/`
case $cs_gettext_version in
  0.17*)
    for d in . libple
    do
      cp -p $d/configure.ac $d/configure.ac.tmp
      sed -e s/AM_GNU_GETTEXT_VERSION.*/AM_GNU_GETTEXT_VERSION\(\[$cs_gettext_version\]\)/g $d/configure.ac.tmp > $d/configure.ac
    done
    ;;
  *)
    ;;
esac

# Prefer autoreconf to separate stages when possible

type autopoint > /dev/null 2>&1

if test $? = 0 ; then

  autoreconf -vif $@

else

  # To add gettext support, use :
  # gettextize -f -c --no-changelog --intl
  # rm -f config/gettext.m4

  # To use an external gettext version, do not use --intl
  # To use a link instead of copy, do not use -c

  if [ ! -f config/gettext.m4 ]; then
    echo "running gettextize"
    \rm -rf configure.ac~ Makefile.am~
    sed -e "s/read dummy/# read dummy/" `which gettextize` > ./tmp_gettextize
    chmod +x ./tmp_gettextize
    ./tmp_gettextize -f -c --no-changelog
    if [ -f configure.ac~ ]; then
      mv configure.ac~ configure.ac
    fi
    if [ -f Makefile.am~ ]; then
      mv Makefile.am~ Makefile.am
    fi
    rm -rf po/*~ tmp_gettextize
  fi

  echo "running aclocal"
  aclocal -I config

  echo "running autoconf"
  autoconf

  if [ ! -f config/ltmain.sh ]; then
    echo "running libtoolize"
    libtoolize --force --copy
  fi

  echo "running autoheader"
  autoheader

  echo "running automake"
  automake -a -c

fi

case $cs_gettext_version in
  0.17*)
    for d in . libple
    do
      \mv configure.ac.tmp configure.ac
    done
    ;;
  *)
    ;;
esac

# Remove cache directory
\rm -rf autom4te.cache
