#!/bin/bash
#
# Check if all required components are present to build Listaller
#
# syntax :
#    ./configure <options> [parameters]
set -e
OPTION_SPEC="help,enable-qt,enable-libuild,enable-tests,enable-test-depman,enable-test-security,prefix:,libdir:,cmake-options:"
PARSED_OPTIONS=$(getopt -n "$0" -a -o h --l "$OPTION_SPEC" -- "$@")

eval set -- "$PARSED_OPTIONS"

function usage
{
  echo "Usage:"
  echo " ./prepare <options> [parameters]"
  echo "Use --enable-<option> to enable features for build."
}

if [ $? != 0 ] ; then usage ; exit 1 ; fi

while true ; do
	case "$1" in
		-h|--help )  usage; exit 0;;
		--enable-qt )  ENABLE_QT=1; shift; ;;
		--enable-libuild )  ENABLE_LIBUILD=1; shift; ;;
		--enable-tests ) ENABLE_TESTS=1; shift; ;;
		--enable-test-depman ) ENABLE_DMAN_TEST=1; shift; ;;
		--enable-test-security ) ENABLE_SEC_TEST=1; shift; ;;
		--prefix ) case "$2" in
			    "") echo "prefix parameter needs an argument!"; exit 3 ;;
			     *) export prefix=$2 ; shift 2 ;;
			   esac ;;
		--libdir ) case "$2" in
			    "") echo "libdir parameter needs an argument!"; exit 3 ;;
			     *) export libdir=$2 ; shift 2 ;;
			   esac ;;
		--cmake-options ) case "$2" in
			    "") echo "CMake-Options need an argument!"; exit 3 ;;
			     *) export cmakeoptn=$2 ; shift 2 ;;
			   esac ;;

		--) shift ; break ;;
		* ) echo "ERROR: unknown flag $1"; exit 2;;
	esac
done

if [ ! -e "$(pwd)/Makefile.in" ]; then
  echo "Makefile template was not found."
  echo "Please cd to the Listaller source directory."
  exit 8
fi

CMAKE=$(which cmake)
if [[ $? -gt 0 ]]; then
  echo "CMake was not found! Please install cmake."
  exit 8
fi

sed "s#%PREFIX%#$prefix#" Makefile.in > Makefile

CMAKE_OPTIONS=$cmakeoptn
if [ "$ENABLE_LIBUILD" = "1" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DLIBUILD=ON"
fi
if [ "$ENABLE_TESTS" = "1" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DTESTS=ON"
fi
if [ "$ENABLE_DMAN_TEST" = "1" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DTEST_DEPMANAGER=ON"
fi
if [ "$ENABLE_SEC_TEST" = "1" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DTEST_SECURITY=ON"
fi
if [ "$ENABLE_QT" = "1" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DQT=ON"
fi
if [ -n "$prefix" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DCMAKE_INSTALL_PREFIX=$prefix"
fi
if [ -n "$libdir" ]; then
 CMAKE_OPTIONS="$CMAKE_OPTIONS -DLIB_INSTALL_DIR=$libdir"
fi

mkdir -p build
cd build
cmake $CMAKE_OPTIONS ..
cd ..

echo
echo "Summary:"
echo
echo "Listaller will be built with the following features:"
echo " GLib Library:       enabled"
echo " Command-Line Tools: enabled"
if [ "$ENABLE_TESTS" = "1" ]; then
 echo " Unit Tests:         enabled"
else
 echo " Unit Tests:         disabled"
fi
if [ "$ENABLE_QT" = "1" ]; then
 echo " Qt4 Widgetset:      enabled"
else
 echo " Qt4 Widgetset:      disabled"
fi
echo
echo "You can now run make"
echo "then make install"
echo
