#! /bin/sh

prefix=/usr/local
config=release
sse2=sse2
QMAKE=

usage="Usage: configure [-prefix DIR] [-qmake PATH] [-debug]

Options:

  -prefix DIR   Set the instalation directory to DIR (default: /usr/local)
  -qmake PATH   Full path to the 'qmake' program (default: autodetect)
  -debug        Build with debugging symbols
  -no-sse2      Do not compile with use of SSE2 instructions
"

while test $# -gt 0; do
  case $1 in
    -prefix )
      prefix=$2
      shift ; shift
      ;;
    -qmake )
      QMAKE=$2
      shift; shift
      ;;
    -debug )
      config=debug
      shift
      ;;
    -no-sse2 )
      sse2=no-sse2
      shift
      ;;
    -help | --help )
      echo "$usage"
      exit
      ;;
    * )
      echo "*** ERROR: Unrecognized option '$1'" >&2
      echo "$usage"
      exit 1
      ;;
  esac
done

echo "Testing for qmake..."

paths=

if test -n "$QMAKE"; then
  if test -x "$QMAKE"; then
    paths=$QMAKE
  else
    echo "*** ERROR: '$QMAKE' is not an executable program." >&2
    exit 1
  fi
else
  for i in qmake qmake-qt4; do
    if which $i >/dev/null 2>/dev/null; then
      paths="$paths `which $i`"
    fi
    if test -n "$QTDIR"; then
      if test -x "$QTDIR/bin/$i"; then
        paths="$paths $QTDIR/bin/$i"
      fi
    fi
  done
fi

if test -z "$paths"; then
    echo "*** ERROR: Cannot find 'qmake' in your PATH." >&2
    exit 1
fi

QMAKE=

for i in $paths; do
  version=`$i -query QT_VERSION`
  if test "$version" != "**Unknown**"; then
    major=`echo $version | sed -e "s/\([0-9][0-9]*\).*/\1/"`
    minor=`echo $version | sed -e "s/[0-9][0-9]*\.\([0-9][0-9]*\).*/\1/"`
    if test $major -eq 5; then
      QMAKE=$i
      break
    fi
  fi
done

if test -z "$QMAKE"; then
    echo "*** ERROR: Cannot find 'qmake' from Qt 5." >&2
    exit 1
fi

echo "Using $QMAKE (Qt $version)"

if test -f fraqtive.pro; then
  PROJECT=fraqtive.pro
elif test -f ../fraqtive.pro; then
  PROJECT=../fraqtive.pro
else
    echo "*** ERROR: Cannot find 'fraqtive.pro' in current or parent directory." >&2
    exit 1
fi

echo "Writing configuration file..."

echo "# this file was generated by configure" >config.pri
echo "CONFIG += $config $sse2" >>config.pri
echo "PREFIX = $prefix" >>config.pri

echo "Generating Makefiles..."

if $QMAKE -recursive $PROJECT; then
    echo
    echo "Configure finished. Run 'make' now."
    echo
else
    echo "*** ERROR: Running 'qmake' failed." >&2
    exit 1
fi
