#!/bin/sh

# This is more portable than `which' but comes with
# the caveat of not(?) properly working on busybox's ash:
have_command()
{
    command -v "$1" >/dev/null 2>&1
}

unset bs_srcdir
if test X"`dirname / 2>/dev/null`" = X"/"; then
  bs_scrdir=`dirname $0`
else
  case $0 in
    */*) bs_scrdir=`echo $0 | ${SED-sed} -n -e 's|/[^/]*$||p'` ;;
    *) bs_scrdir='.' ;;
  esac
fi

test -n "$bs_scrdir" && cd "$bs_scrdir" || echo "Warning: cannot detect sources directory" 1>&2

if test ! -f './configure.ac'; then
  echo "Error: no 'configure.ac' found. Wrong sources directory?" 1>&2
  exit 2
fi
if test ! -f './src/include/microhttpd.h'; then
  echo "Error: src/include/libmicrohttpd.h not found. Wrong sources directory?" 1>&2
  exit 2
fi

if have_command uncrustify; then
    if test -f uncrustify.cfg; then
      echo "Uncrustify configuration already exists, skipping installation from the upstream file."
    else
      echo "Installing libmicrohttpd uncrustify configuration"
      ln -s contrib/uncrustify.cfg uncrustify.cfg || \
        cp contrib/uncrustify.cfg uncrustify.cfg || \
        echo "Failed to install uncrustify configuration file" 1>&2
    fi
    if test -f uncrustify.cfg; then
      if test -d '.git'; then
        if test -f .git/hooks/pre-commit; then
          echo "Pre-commit git hook already exists, skipping installation from the upstream file."
        else
          echo "Installing uncrustify pre-commit git hook"
          ln -s ../../contrib/uncrustify_precommit .git/hooks/pre-commit || \
            cp ../../contrib/uncrustify_precommit .git/hooks/pre-commit || \
            echo "Failed to install pre-commit git hook" 1>&2
        fi
      else
        echo "No '.git' directory found, skipping installation of pre-commit git hook."
      fi
    fi
else
    echo "Uncrustify not detected, hook not installed. Please install uncrustify if you plan on doing development."
fi

WANT_AUTOCONF=latest
WANT_AUTOMAKE=latest
export WANT_AUTOCONF
export WANT_AUTOMAKE

aclocal -I m4 --install && \
  libtoolize -c -i -v && \
  autoconf && \
  autoheader && \
  automake -a -c --gnu || \
  echo "Trying with autoreconf..." &&
  autoreconf -vi ${1+"$@"} || \
  echo "*** Failed to build autoconf output files ***" >&2
