#!/bin/sh

debug_mode=""
release_mode=""
invalid_options=""
prefix="/usr/local"

while [ $# -ne 0 ]; do
	if [ "$1" = "--debug" ]; then
		debug_mode=on
	elif [ "$1" = "--release" ]; then
		release_mode=on
	elif [ "$1" = "--prefix" ]; then
		prefix="$2"
		shift
	elif echo "$1" | grep -q "^--prefix="; then
		prefix=`echo "$1" | sed -e 's/^--prefix=//'`
	else
		echo "Error: invalid option \"$1\"."
		invalid_options=on
	fi

	shift
done


if [ -n "$debug_mode" -a -n "$release_mode" ]; then
	echo "Error: you cannot specify both debug and release mode."
	echo ""
	invalid_options="on"
elif [ -z "$debug_mode" -a -z "$release_mode" ]; then
	invalid_options="on"
fi


if [ -n "$invalid_options" ]; then
	cat <<EOF
This project is built using CMake.
If you are familiar with CMake, you may invoke it directly.
If you are not familiar with CMake, this script can help select the best
options for CMake and invoke it for you.

Options:
	--debug          build an executable with debugging information.
	--release        build an optimized executable for release.
	--prefix <path>  specify the installation prefix.
EOF
	exit 1
fi


srcdir=`dirname $0`
echo "Checking for CMake..."
cmake >/dev/null 2>/dev/null
if [ $? -eq 127 ]; then
	echo "CMake not found.  CMake is required."
	exit 1
fi
echo "CMake found."
echo ""


if [ -n "$release_mode" ]; then
	options="-DCMAKE_BUILD_TYPE=release"
else
	options="-DCMAKE_BUILD_TYPE=debug"
fi
options="$options -DCMAKE_INSTALL_PREFIX=$prefix"


# Work around a Mac bug.  "make clean" doesn't clean the .app, and CMake
# will regenerate the .app structure during the configure phase anyway.
rm -rf src/FreeSynd.app


echo "Invoking CMake..."
cmake "$srcdir" $options
if [ $? -ne 0 ]; then
	echo "A CMake error occurred."
	exit 1
fi

echo "CMake successful."
echo ""
make clean
echo "Type \"make\" to build."
exit 0
