#!/bin/sh

set -e

if test $# -lt 3 -o $0 != "./install_qt_mobility"; then
  echo "Usage: ./install_qt_mobility <path-to-zip> [-qt <target-qt-dir>] [-sdk <target-sdk-dir>] [-sdk <another-sdk-dir>] [-mobility <target-mobility-dir>]"
  echo " e.g.: ./install_qt_mobility qt-mobility-symbian-opensource-1.1.0.zip -qt ~/symbian-sdks/qt -sdk ~/symbian-sdks/s60_31 -mobility ~/symbian-sdks/qt_mobility"
  exit 1
fi

SRC=$1
shift

QTDIRS=""
MOBILITY=""

while [ $# -gt 1 ]; do
	if [ "$1" = "-qt" ]; then
		QTDIRS="$QTDIRS $2"
		shift 2
	else if [ "$1" = "-sdk" ]; then
		SDKS="$SDKS $2"
		shift 2
	else if [ "$1" = "-mobility" ]; then
		MOBILITY="$2"
		shift 2
	else
		echo Unknown parameter $1
		exit 1
	fi; fi; fi
done
if [ $# -gt 0 ]; then
	echo Unknown parameter $1
	exit 1
fi

QTDIRS=`echo $QTDIRS | sed s:/\$:: | sed 's:/ : :'`
MOBILITY=`echo $MOBILITY | sed s:/\$:: | sed 's:/ : :'`
SDKS=`echo $SDKS | sed s:/\$:: | sed 's:/ : :'`

set -x

### Unzip
mkdir -p qt_temp
unzip -dqt_temp $SRC
DIR=qt_temp/qt-mobility-*
for q in $QTDIRS; do
	cp $DIR/features/mobility.prf.template $q/mkspecs/features/mobility.prf
	cp $DIR/*.sis $q
	QTVER=`echo $q/changes-*`
	QTVER=`basename $QTVER | sed s/changes-//`
	if [ "$QTVER" = "*" ]; then
		QTVER=""
	fi
done
if [ "$QTVER" != "" ]; then
	# Strip the last digit from the version number, assuming compatibility
	# between e.g. 4.7.x
	QTVER=`echo $QTVER | sed 's/\..$//'`
fi
for s in $SDKS; do
	PKG=
	if [ -f $s/epoc32/include/variant/symbian_os_v9.2.hrh ]; then
		PKG=`echo $DIR/qt-mobility-*-qt-$QTVER.?-epoc32-3.1.zip`
		if [ ! -f $PKG ]; then
			PKG=`echo $DIR/qt-mobility-*-epoc32-3.1.zip`
		fi
	else if [ -f $s/epoc32/include/variant/symbian_os_v9.3.hrh ]; then
		PKG=`echo $DIR/qt-mobility-*-qt-$QTVER.?-epoc32-3.2.zip`
		if [ ! -f $PKG ]; then
			PKG=`echo $DIR/qt-mobility-*-epoc32-3.2.zip`
		fi
	else if [ -f $s/epoc32/include/variant/symbian_os.hrh ]; then
		if [ -f $s/epoc32/tools/checklib.exe ]; then
			PKG=`echo $DIR/qt-mobility-*-symbian3-qt-$QTVER.?-epoc32.zip`
			if [ ! -f $PKG ]; then
				PKG=`echo $DIR/qt-mobility-*-qt-$QTVER.?-epoc32-symbian3.zip`
			fi
			if [ ! -f $PKG ]; then
				PKG=`echo $DIR/qt-mobility-*-epoc32-symbian3.zip`
			fi
		else
			PKG=`echo $DIR/qt-mobility-*-qt-$QTVER.?-epoc32-5.0.zip`
			if [ ! -f $PKG ]; then
				PKG=`echo $DIR/qt-mobility-*-epoc32-5.0.zip`
			fi
		fi
	fi; fi; fi
	if [ "$PKG" != "" ] && [ -f $PKG ]; then
		unzip -o -d$s $PKG
		PKGNAME=`basename $PKG | sed s/.zip//`
		if [ -d $s/$PKGNAME/$PKGNAME ]; then
			./mergedir $s/$PKGNAME/$PKGNAME $s
			rmdir $s/$PKGNAME
		else if [ -d $s/$PKGNAME ]; then
			./mergedir $s/$PKGNAME $s
		fi; fi
		echo Unpacked $PKG
	else
		echo No suitable package found for SDK $s
	fi
done
if [ "$MOBILITY" != "" ]; then
	mv $DIR $MOBILITY
fi
rm -rf qt_temp

