#!/bin/sh

gui="optimas_gui"
cmd="optimas"

## loading user's configuration informations
. ./config.in

## A FAIRE : verifier si g++, make, qmake et les bibli ont tous la meme architechture (64 ou 32 bits)
## try : sudo apt-get install qt qwt graphviz
## system architecture (x86_64 or iX86)
lib=lib
arch=`uname -m`
#[ "$arch" = "x86_64" ] && lib=lib64
#echo $lib ; read v
## checking OptiMAS sources directories.
[ ! -d "$cmd" ] && echo "$cmd sources directory not found !" && exit 1
[ ! -d "$gui" ] && echo "$gui sources directory not found !" && exit 1

## looking for make and g++
if [ ! "$(which make)" ]; then
	echo "ERROR: make not found !"
	echo "try to install it using your distribution package manager:"
	echo "e.g. sudo apt-get install make (on Debian/Ubuntu plateforms)"
	echo "or yum install make (on Redhat/Fedora/CentOS plateforms)"
	exit 1
fi

if [ ! "$(which g++)" ]; then
	echo "ERROR: g++ not found !"
	echo "try to install it using your distribution package manager:"
	echo "e.g. apt-get install g++ (on Debian/Ubuntu plateforms)"
	echo "or yum install gcc-c++ (on Redhat/Fedora/CentOS plateforms)"
	exit 1
fi
# g++ --version | head -1 | grep -Eo " [0-9]\.[0-9]\.[0-9]( |$)"

echo

isroot=
## OptiMAS files location:
if [ "$(id -u)" -eq 0 ]	# install as super-user.
then
	isroot="[ \"\$(id -u)\" -ne 0 ] && echo \"Error: this script must be launched as root !\" && exit 1"
	optimas_dir=/usr/share/OptiMAS
	bin_dir=/usr/local/bin #/usr/bin ?
	example_dir=/usr/share/OptiMAS/output
	doc_dir=/usr/share/OptiMAS/doc
	website_dir=/usr/share/OptiMAS/website
	#images_dir=/usr/share/OptiMAS/images
	
else					# install as common user.
	bin_dir=$HOME/bin
	[ ! -e "$bin_dir" ] && mkdir $bin_dir
	[ -e "$bin_dir" -a ! -d "$bin_dir" ] && echo "ERROR: $bin_dir already exists but is not a directory !" && exit 1

	optimas_dir=$HOME/.OptiMAS
	example_dir=$HOME/.OptiMAS/output
	doc_dir=$HOME/.OptiMAS/doc
	website_dir=$HOME/.OptiMAS/website
	#images_dir=$HOME/.OptiMAS/images
	
fi
#echo "optimas_dir : $optimas_dir ; bin_dir : $bin_dir"; echo "isroot : $isroot FIN" ; read v

## create the uninstall script.
uninstallsh="uninstall_optimas.sh"
cat >$bin_dir/$uninstallsh <<FIN
#!/bin/sh
# this script has been generated by $0

$isroot
rm -rf $optimas_dir 2>/dev/null
rm -f $bin_dir/$cmd 2>/dev/null
rm -f $bin_dir/$gui 2>/dev/null
rm -f $bin_dir/$uninstallsh 2>/dev/null

exit 0

FIN
chmod a+x $bin_dir/$uninstallsh

#echo "uninstall script done !"; read v

[ ! -d "$optimas_dir" ] && mkdir -p $optimas_dir
## copy doc output website to optimas_dir
cd $gui
cp -rf input doc output website $optimas_dir
chmod -R a+r $optimas_dir
find $optimas_dir -type d -exec chmod a+x {} \;
cd ..
echo "optimas_dir: " $optimas_dir
echo "bin_dir: " $bin_dir
echo

############## optimas stuff (OptiMAS heavy treatment) ####################

cd $cmd
echo "Building $cmd ..."
make all
[ "$?" -ne 0 ] && echo "ERROR: make failed to build $cmd !" && exit 1

# copy optimas binary file to the bin directory
cp -f bin/$cmd $bin_dir
[ "$?" -ne 0 ] && echo "ERROR: could not copy $cmd in $bin_dir" && exit 1
#cp -rf ../$gui/input $optimas_dir
########################################################################

echo
cd ..

#echo "$cmd done"; read v

if [ "$1" = "--no-gui" ]	# don't install OptiMAS GUI.
then
	echo "$cmd is installed here: $bin_dir/$cmd"
	echo
else						# install OptiMAS GUI.

	################### build optimas_gui (graphical user interface) #####################
	# (headers and libraries pathes for qwt and graphviz may have been specified in config.in)

	# looking for qmake in $PATH
	#qmake_path=$(find $(echo $PATH | tr ':' '\n' | grep bin$) -name "qmake*" -perm /o=x 2>/dev/null)
	echo "checking qmake version and path ..."
	qmake_version=0
	qmake_v=0
	qmake_path=
	for qmake_p in $(find $(echo $PATH | tr ':' '\n' | grep bin$) -name "qmake*" -perm /o=x)
	do
		[ -n "$qmake_p" ] && qmake_v=$($qmake_p -v 2>&1 | head -1 | cut -d" " -f3 | cut -c1)
		[ "$qmake_v" -gt "$qmake_version" ] && qmake_version=$qmake_v && qmake_path=$qmake_p
	done
	if [ -z "$qmake_path" ]; then
		echo "ERROR: qmake not found !"
		echo "the Qt4 development package may not be installed..."
		echo "try to install it using your distribution package manager:"
		echo "e.g. apt-get install libqt4-dev (on Debian/Ubuntu plateforms)"
		echo "or yum install qt4-devel (on Redhat/Fedora/CentOS plateforms)"

		exit 1
	fi
	
	echo "qmake found: $qmake_path"

	## checking Qt version
	qt_required="4.4.3"
	qt_installed=$($qmake_path -v | grep -Eio "qt[^0-9]+[0-9]\.[0-9]\.[0-9]" | awk '{print $NF}')
	oldest_qt=$(echo -e "$qt_installed\n$qt_required" | sort | head --line=1)
	if [ "$oldest_qt" != "$qt_required" ] # qt_installed is older
	then
		echo
		echo "WARNING ! Required Qt version is $qt_required !"
		echo "The installed version is $qt_installed and has never been tested ..."
		echo "continue anyway ? (y/N): " ; read resp
		if [ "$resp" != "y" -a "$resp" != "Y" ]
		then
			echo
			echo "OptiMAS GUI installation aborted."
			$bin_dir/$uninstallsh
			echo
			echo "Installed elements have been removed."
			
			exit 2
		fi
	fi
	#echo "qt_installed : $qt_installed"; read v
	echo

	# ----------- looking for qwt and graphviz include paths
	#qwt_include_path=$(sed -n 's/^qwt_include_path=\(.*\)$/\1/p' config.in)
	echo "checking qwt and graphviz include directories ..."
	# see if qwt and graphviz include pathes have been set in config.in and check these pathes.
	if [ -n "$qwt_include_path" ]
	then
		if [ ! -d "$qwt_include_path" ]
		then
			echo "ERROR: the qwt include path specified in config.in does not exist !"
			exit 1
		fi
	fi
	#graphviz_include_path=$(sed -n 's/^graphviz_include_path=\(.*\)$/\1/p' config.in)
	if [ -n "$graphviz_include_path" ] 
	then
		if [ ! -d "$graphviz_include_path" ]
		then
			echo "ERROR: the graphviz include path specified in config.in does not exist !"
			exit 1
		fi
	fi

	echo

	# if include pathes are not set in config.in, perform a search in usual include directories.
	[ -z "$qwt_include_path" ] && qwt_include_path=$(dirname $(find -H /usr/include /usr/local/include -type f -name qwt.h 2>/dev/null) 2>/dev/null)
	[ -z "$qwt_include_path" ] && qwt_include_path=$(dirname $(find -H /usr/* -type f -name qwt.h 2>/dev/null) 2>/dev/null)
	if [ -z "$qwt_include_path" ]; then
		echo "ERROR: qwt include directory not found !"
		echo "you may have to specify it in config.in file..."
		echo "or try to install the qwt development package using your distribution package manager:"
		echo "e.g. apt-get install libqwt5-qt4-dev (on Debian/Ubuntu platforms)."
		echo "or yum install qwt5-qt4-devel (on Redhat/Fedora/CentOS platforms)."		
		exit 1
	fi
	[ -z "$graphviz_include_path" ] && graphviz_include_path=$(dirname $(find -H /usr/include /usr/local/include -type f -name gvc.h 2>/dev/null) 2>/dev/null)
	[ -z "$graphviz_include_path" ] && graphviz_include_path=$(dirname $(find -H /usr/* -type f -name gvc.h 2>/dev/null) 2>/dev/null)
	if [ -z "$graphviz_include_path" ]; then
		echo "ERROR: graphviz include directory not found !"
		echo "you may have to specify it in config.in file..."
		echo "or try to install the graphviz development package using your distribution package manager:"
		echo "e.g. apt-get install libgraphviz-dev (on Debian/Ubuntu platforms)."
		echo "or yum install graphviz-devel (on Redhat/Fedora/CentOS platforms)."
		exit 1
	fi
	echo "qwt include path found: $qwt_include_path"
	echo "graphviz include path found: $graphviz_include_path"

	echo

	#echo ""; read v

	# ----------- looking for qwt and graphviz libs paths
	echo "checking qwt and graphviz libraries ..."
	# see if qwt and graphviz lib pathes have been set in config.in and check these pathes.
	if [ -n "$qwt_lib" ]
	then
		if [ ! -f "$qwt_lib" ]
		then
			echo "ERROR: the qwt shared library specified in config.in does not exist !"
			exit 1
		fi
	fi
	if [ -n "$graphviz_lib" ]
	then
		if [ ! -f "$graphviz_lib" ]
		then
			echo "ERROR: the graphviz shared library specified in config.in does not exist !" 
			exit 1
		fi
	fi

	echo


	# A FAIRE : faire une boucle sur /usr/$lib /$lib /usr/local/$lib et interrompre le find des qu'on trouve.
	# if lib pathes are not set in config.in, perform a search in usual lib directories.
	#[ -z "$qwt_lib" ] && qwt_lib=$(find /usr/lib /lib /usr/local/lib -type f -name "libqwt-*.so.*" -or -type f -name "libqwt.so.*" 2>/dev/null)
	#[ -z "$qwt_lib" ] && qwt_lib=$(find -H /usr/$lib /$lib /usr/local/$lib -type f -name "libqwt[-.]*so.*" 2>/dev/null)
	[ -z "$qwt_lib" ] && qwt_lib=$(find -L /lib /usr/lib /usr/local/lib -type f -regex ".*libqwt5?[-.].*so$" 2>/dev/null | tail -n 1)
	[ -z "$qwt_lib" ] && echo "ERROR: qwt library not found !" && echo "you may have to specify it in config.in file..." && exit 1
	#[ -z "$graphviz_lib" ] && graphviz_lib=$(find -H /$lib /usr/$lib /usr/local/$lib -type f -name "libgvc.so*" 2>/dev/null)
	[ -z "$graphviz_lib" ] && graphviz_lib=$(find -L /lib /usr/lib /usr/local/lib -type f -name "libgvc.so" 2>/dev/null | tail -n 1)
	[ -z "$graphviz_lib" ] && echo "ERROR: graphviz library libgvc.so not found !" && echo "you may have to specify it in config.in file..." && exit 1

	echo "qwt library found: $qwt_lib"
	echo "graphviz library found: $graphviz_lib"

	qwt_lib_name=$(basename $qwt_lib | sed -e 's/lib\(.*\)\.so.*/\1/')
	graphviz_lib_name=$(basename $graphviz_lib | sed -e 's/lib\(.*\)\.so.*/\1/')
	graphviz_lib_dir=$(dirname $graphviz_lib | tail -n 1)
	graph_lib_name= # either graph or cgraph
	if [ -f "$graphviz_lib_dir/libgraph.so" ]
	then
		graph_lib_name=graph
	elif [ -f "$graphviz_lib_dir/libcgraph.so" ]
	then
		graph_lib_name=cgraph
	else
		echo "ERROR: neither libgraph.so nor libcgraph.so was found in $graphviz_lib_dir !" 
		exit 1
	fi

	echo

	#echo "qwt_lib_name $qwt_lib_name graphviz_lib_name : $graphviz_lib_name"; read v

	cd $gui

# write optimas_gui.pro (please don't tabulate)
cat >$gui.pro <<FIN
TEMPLATE = app
TARGET = $gui
QT += core gui
QT *= svg

# qDebug: CONFIG += console
linux-g++|linux-g++-32|linux-g++-64 { 
	INCLUDEPATH += $qwt_include_path/ $graphviz_include_path/
	LIBS += -l$qwt_lib_name -l$graphviz_lib_name -l$graph_lib_name
	QMAKE_CXXFLAGS_RELEASE -= -g
	QMAKE_CFLAGS_RELEASE -= -g
}
macx {
    INCLUDEPATH += /opt/local/include/ \
        /opt/local/include/qwt/ \
        /opt/local/include/graphviz
    LIBS += -L/opt/local/lib -lqwt -lgvc -lgraph #-lcdt #-lpathplan
    LIBS += -L/opt/local/lib/graphviz -lgvplugin_dot_layout -lgvplugin_pango 
    LIBS += -L/opt/local/lib/pango/1.6.0/modules/pango-basic-fc.so
}
win32 { 
	INCLUDEPATH += "C:/qwt-5.2.2/src" "C:/Program Files/Graphviz 2.28/include/graphviz"
	LIBS += -L"C:/qwt-5.2.2/lib" -lqwt5 -L"C:/Program Files/Graphviz 2.28/bin" -lgvc -lgraph -lpathplan -lcdt -L"C:/Program Files/Graphviz 2.28/lib/release/lib" -lgvc
	DEFINES += QWT_DLL
}
HEADERS += headers/FillMdWindow.h \
    headers/IndexWindow.h \
    headers/OImageViewer.h \
    headers/QtlWeightWindow.h \
    headers/HistoColorWindow.h \
    headers/TruncationOptionWindow.h \
    headers/CrossOptionWindow.h \
    headers/TableViewWindow.h \
    headers/FindDialog.h \
    headers/OTableWidget.h \
    headers/CompResultsWindow.h \
    headers/ComplementationWindow.h \
    headers/VisualizationWindow.h \
    headers/BoxPlotItem.h \
    headers/utils.h \
    headers/MainWindow.h \
    headers/LicenseWindow.h \
    headers/ImportWindow.h \
    headers/HistogramItem.h \
    headers/AddListDialog.h \
    headers/AboutWindow.h \
    headers/muParserBase.h \
	headers/muParserBytecode.h \
	headers/muParserCallback.h \
	headers/muParserDef.h \
	headers/muParserError.h \
	headers/muParserFixes.h \
	headers/muParser.h \
	headers/muParserStack.h \
	headers/muParserTemplateMagic.h \
	headers/muParserToken.h \
	headers/muParserTokenReader.h
SOURCES += src/FillMdWindow.cpp \
    src/IndexWindow.cpp \
    src/OImageViewer.cpp \
    src/QtlWeightWindow.cpp \
    src/HistoColorWindow.cpp \
    src/TruncationOptionWindow.cpp \
    src/CrossOptionWindow.cpp \
    src/TableViewWindow.cpp \
    src/FindDialog.cpp \
    src/OTableWidget.cpp \
    src/CompResultsWindow.cpp \
    src/ComplementationWindow.cpp \
    src/VisualizationWindow.cpp \
    src/BoxPlotItem.cpp \
    src/utils.cpp \
    src/MainWindow.cpp \
    src/main.cpp \
    src/LicenseWindow.cpp \
    src/ImportWindow.cpp \
    src/HistogramItem.cpp \
    src/AddListDialog.cpp \
    src/AboutWindow.cpp \
    src/muParserBase.cpp \
	src/muParserBytecode.cpp \
	src/muParserCallback.cpp \
	src/muParser.cpp \
	src/muParserError.cpp \
	src/muParserTokenReader.cpp
FORMS += ui/fillMdWindow.ui \
    ui/indexWindow.ui \
    ui/histoColorWindow.ui \
    ui/qtlWeightWindow.ui \
    ui/truncationOptionWindow.ui \
    ui/crossOptionWindow.ui \
    ui/tableViewWindow.ui \
    ui/compResultsWindow.ui \
    ui/complementationWindow.ui \
    ui/visualizationWindow.ui \
    ui/aboutWindow.ui \
    ui/importWindow.ui \
    ui/licenseWindow.ui \
    ui/mainWindow.ui
RESOURCES += ui/configdialog.qrc

FIN

	echo "$gui.pro done"
	echo

	#echo ""; read v

	## writing Makefile via qmake 
	$qmake_path $gui.pro

	## build optimas_gui
	make
	[ $? -ne 0 ] && echo "ERROR: make failed to build $gui !" && exit 1

	echo "binary $gui done"
	echo
	########################################################################
	#echo ""; read v
	###################### INSTALL optimas_gui #############################

	mv -f $gui $bin_dir;
	[ "$?" -ne 0 ] && echo "Error: could not copy $gui in $bin_dir ..." && exit 1

	cd ..
	########################################################################
	
	echo "$cmd and $gui are installed here: $bin_dir"
fi # end of if [ "$1" = "--no-gui" ]
#echo ""; read v
## checking if bin_dir is in the PATH and/or user profile file.
echo $PATH | grep -q "$bin_dir"
if [ "$?" -ne 0 ] # bin_dir is not in the PATH
then
	echo "$bin_dir is not in the PATH environment variable"
	profile=
	if [ -f "$HOME/.${SHELL}_profile" ]; then
		profile="$HOME/.${SHELL}_profile"
	elif [ -f "$HOME/.${SHELL}_login" ]; then
		profile="$HOME/.${SHELL}_login"
	elif [ -f "$HOME/.profile" ]; then
		profile="$HOME/.profile"
	fi
	
	if [ -n "$profile" ] # user profile exists but $bin_dir is not in the PATH
	then
		. $profile
		echo $PATH | grep -q "$bin_dir"
		if [ "$?" -ne 0 ]  # do not update $profile once more in case of successive execution of this script.
		then
			#tmp="${bin_dir/$HOME/\$HOME}" # <= bashism !
			tmp=$(echo "$bin_dir" | perl -ne 's/$ENV{"HOME"}/\$HOME/g ; chomp; print')
			#echo "you may want to edit $profile and add the following lines:"
			echo >> $profile
			echo "if [ -d \"$tmp\" ] ; then" >> $profile
			echo "	PATH=\"\$PATH:$tmp\"" >> $profile
			echo "fi" >> $profile
		fi
	else # user profile does not exists
		cp -f ./user_profile $HOME/.profile
		profile="$HOME/.profile"
	fi
	echo -ne "Restart your session or type:\n. $profile\nto include $bin_dir in the PATH variable.\n"
	echo
	echo -ne "Then "
fi
#echo ""; read v
echo -ne "To launch $cmd or $gui, just type from the commande line:\n\
$cmd [arguments]\n\
or\n\
$gui\n\n\
See README file and $website_dir/index.html for OptiMAS GUI documentation.\n\n"

echo "To uninstall OptiMAS, type the command:"
echo "$bin_dir/$uninstallsh"
echo

exit 0
