#!/bin/sh

#Use the correct qmake and debug/release mode
QTVERSION=`grep QTVERSION.*= <../../config.pro |sed 's/[^=]*= *//'`

if [ "$QTVERSION" = "qt3" ]; then
 rm -f Makefile.qsa
else
 echo Skipping QSA-1.1.5
 #create dummy makefile
 echo staticlib: > Makefile.qsa
 exit 0
fi

OPT_HELP=no
OPT_FORCE_THREAD=no

# parse arguments
for a in "$@"; do
    case "$a" in
    -help|--help)
	OPT_HELP=yes
	;;
    -thread|--thread)
	OPT_FORCE_THREAD=yes
	;;
    *)
        # passed to configure2
	;;
    esac
done

if [ "$OPT_HELP" = "yes" ]; then
    cat <<EOF
Usage: configure [options]
Options:
  -help         Display this information
  -thread       Force a threaded configuration.
  -prefix       Installation prefix
  -qmake        QMake to invoke
  -no-ide       Does not compile QSA Workbench into QSA.
  -release 	Forces release build.
  -debug 	Forces debug build.
EOF
   exit 0
fi

if [ -z $QTDIR ]
then
    echo "Can't find Qt library. No QTDIR set."
    exit 1
else
    echo "Using Qt library in $QTDIR."
fi

QMAKE_CACHE=${QTDIR}/.qmake.cache
if [ -f ${QMAKE_CACHE} ]; then
    rm -f .qmake.cache
    ln -s ${QMAKE_CACHE} .qmake.cache
else
    echo Trying my best without a .qmake.cache file
fi

# force thread build if requested
if [ "$OPT_FORCE_THREAD" = "yes" ]; then
   CONF="CONFIG+=thread"
else
   CONF="CONFIG+="
fi

find src -name Makefile -exec rm {} \;

#Use the correct qmake and debug/release mode
E_RELEASE=`grep E_RELEASE= <../Makefile.flags |sed s/[^=]*=//`
QMAKE=`grep QMAKE= <../Makefile.flags |sed s/[^=]*=//`

#debug/release
if [ "$E_RELEASE" = "yes" ]; then
   BUILD="-release"
else
   BUILD="-debug"
fi

# build 2nd stage configure tool
echo "Building 2nd stage configure"
cd configure2
$QMAKE "${CONF}" && make > /dev/null
if [ $? -gt 0 -o ! -x configure2 ]; then
    exit 1
fi

# invoke 2nd stage
cd ..
configure2/configure2 -qmake "$QMAKE" $BUILD "$@" || exit 1

# (cd examples; qmake "${CONF}")
# (cd src/ide; qmake "${CONF}")
# (cd src; qmake "${CONF}")
# qmake "${CONF}" qsa.pro

# echo "Libraries will be installed in $QTDIR/lib"
