#!/usr/bin/env bash
# $Id: automake-ify,v 1.7 2011/11/02 07:35:46 friedman Exp $

run()
{
  echo ${PS4-+} ${1+"$@"} 1>&2
  ${1+"$@"} || exit $?
}

manual()
{
  if ! [ -d config ]; then
    mkdir config
  fi

  if [ -d m4 ]; then
    run aclocal -I config -I m4
  else
    run aclocal -I config
  fi

  if [ -d po ]; then
    if type -P autopoint > /dev/null; then
      run autopoint  --force
    else
      run gettextize --force --no-changelog
    fi
  fi

  run autoheader -W all

  if grep 'AM_PROG_LIBTOOL' configure.in > /dev/null 2>&1; then
    if grep -i 'libltdl' configure.in > /dev/null 2>&1; then
      if [ -d libltdl ]; then
        rm -rf libltdl
      fi
      run libtoolize -c --ltdl --subproject
    else
      run libtoolize -c
    fi
  fi

  if [ -f Makefile.am ]; then
    run automake --add-missing --copy
  fi

  run autoconf -W all
}

main()
{
  if type -P autoreconf > /dev/null; then
    set autoreconf --verbose --force --install -W all
    if [ -d m4 ]; then
      set "$@" -I m4
    fi
    run "$@"
  else
    manual
  fi
}

main "$@"

# eof
