#!/bin/sh

# parsing options

TEMP=`getopt -o p:b:l:q:h --long prefix:,bindir:,libdir:,qtdir:,help \
-n 'configure' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true; do
	case "$1" in
		-p|--prefix) PREFIX=$2; shift 2 ;;
		-b|--bindir) BINDIR=$2; shift 2 ;;
		-l|--libdir) LIBDIR=$2; shift 2 ;;
		-q|--qtdir) QTDIR=$2; shift 2 ;;
		-h|--help) cat <<EOT
Help is missing - please write it!
EOT
			exit
			;;
		--) shift ; break ;;
		*) echo "unknown parameter $1";;
	esac
done

echo Configuring Psi ...

PREFIX=${PREFIX:-/usr/local}
BINDIR=${BINDIR:-$PREFIX/bin}
LIBDIR=${LIBDIR:-$PREFIX/share/psi}

if [ -z "$QTDIR" ]; then
	echo 
	echo \$QTDIR not set... trying to find qt manually
	qm=`type -p qmake`
	if [ -x "$qm" ]; then
		echo qmake found in $qm
	else 
		echo
		echo Please install Qt 3 development utilities. You may
		echo download them either from the vendor of your operating
		echo system or from www.trolltech.com
		exit 1;
	fi
	for p in /usr/lib/qt /usr/share/qt /usr/local/lib/qt /usr/local/share/qt /usr/lib/qt3 /usr/local/lib/qt3 ; do
		if [ -e "$p/mkspecs/linux-g++/qmake.conf" ]; then
			echo qmake.conf found in $p/mkspecs/linux-g++/qmake.conf
			QTDIR=$p
			break;
		fi;
	done
	if [ -z "$QTDIR" ]; then
		echo Unable to find qmake.conf. Please set QTDIR
		echo manually. Perhaps you need to install Qt 3
		echo development utilities. You may download them either
		echo from the vendor of your operating system or from
		echo www.trolltech.com
		exit 1;
	fi
else 
	if [ ! -x "$QTDIR/bin/qmake" ]; then
		echo \$QTDIR points to $QTDIR, but $QTDIR/bin/qmake
		echo does not exist! Please point \$QTDIR to the correct
		echo location, or unset it if qmake is in your search path.
		exit 1;
	else
		qm=$QTDIR/bin/qmake
	fi
fi

# create Makefile, configure.pri and config.h

cat >Makefile <<EOT
all:
	QTDIR=$QTDIR make -C src

install:
	QTDIR=$QTDIR make -C src install

clean:
	QTDIR=$QTDIR make -C src clean

distclean: clean
	-rm Makefile
	-rm configure.pri

EOT

cat >src/configure.pri <<EOT
libfiles.path=$LIBDIR
libfiles.files=../image ../iconsets ../sound ../certs ../README ../COPYING

target.path=$BINDIR

INSTALLS = libfiles target

EOT

cat >src/config.h <<EOT
#define LIBDIR "$LIBDIR"
EOT
# run qmake

( 
	cd src
	$qm psi.pro
)
# here we are back from src/


echo Done!

