#!/bin/bash
# create the appropriate .bash_profile/.bashrc entries for environment variables to use PluginFlow


SYSTEM=`uname`
CPU=`uname -m`
TMPFILE="/tmp/PLF_INSTALL.$$"
echo "### PluginFlow modifications (automatically generated)" > $TMPFILE
if [ $SYSTEM = "Darwin" ]; then
    MACOS=1
    RCFILE=bash_profile
    YN="[y/N]"
    QTCORENAME="QtCore"
    LIBSUFFIX=".dylib"
else
    RCFILE=bashrc
    YN="[Y/n]"
    LIBSUFFIX=".so"
    QTCORENAME="libQtCore.so"
fi

if [ -f $HOME/.$RCFILE ]; then
    if grep -q "### PluginFlow modifications (automatically generated)" $HOME/.$RCFILE; then
        echo ".$RCFILE contains settings from an earlier run of this script. Should I remove them? [Y/n]"
        read answer
        if [ ! $answer ] || [ $answer = "y" ] || [ $answer = "Y" ]; then
            OLDMOD_START=`grep -n "### PluginFlow modifications (automatically generated)" $HOME/.$RCFILE | awk '{split($1,array,":"); print array[1]}'`
            OLDMOD_END=`grep -n "### End of PluginFlow modifications" $HOME/.$RCFILE | awk '{split($1,array,":"); print array[1]}'`
            cp -i $HOME/.$RCFILE $RCFILE.old
            head -n $[$OLDMOD_START - 1] $RCFILE.old > $HOME/.$RCFILE
            tail -n $[`wc -l $RCFILE.old | awk '{print $1}'`-$OLDMOD_END] $RCFILE.old >> $HOME/.$RCFILE
            echo "Removed old entries. Please open a new shell and run this script again."
            exit
        fi
    fi
fi

if [ $PLF_BASE ]; then
    echo "You already have settings for PluginFlow on your system"
    echo "Should I [e]xit here so you can clean up your .$RCFILE (recommended) or should I [c]ontinue anyway and clutter up your $RCFILE?"
    read answer
    if [ ! $answer ] || ([ $answer != "c" ] && [ $answer != "C" ]); then exit 1; fi
fi

echo "Include Qt-support (currently only useful with OpenScientist)? $YN:"
read WITHQT
echo "Use OpenScientist for histogramming? $YN:"
read WITHOSC

if [ ! $WITHQT ]; then
    if [ $MACOS ]; then
        WITHQT='n'
    else
        WITHQT='y'
    fi
fi
if [ ! $WITHOSC ]; then
    if [ $MACOS ]; then
        WITHOSC='n'
    else
        WITHOSC='y'
    fi
fi

if [ $WITHQT = 'n' ]; then unset WITHQT; fi
if [ $WITHOSC = 'n' ]; then unset WITHOSC; fi

# Basic settings
echo "export PLF_BASE=$PWD" >> $TMPFILE
echo "export PATH=\$PLF_BASE/Controller:\$PATH" >> $TMPFILE
if [ $MACOS ]; then
    echo "export DYLD_LIBRARY_PATH=\$PLF_BASE/Controller:\$PLF_BASE/Base:\$PLF_BASE/Aida:\$DYLD_LIBRARY_PATH" >> $TMPFILE
else
    echo "export LD_LIBRARY_PATH=\$PLF_BASE/Controller:\$PLF_BASE/Base:\$PLF_BASE/Aida:\$LD_LIBRARY_PATH" >> $TMPFILE
fi
echo >> $TMPFILE

# Qt settings
if [ $WITHQT ]; then
    if Controller/check_path.pl -q $LD_LIBRARY_PATH:$DYLD_LIBRARY_PATH:/lib:/usr/lib:/usr/local/lib $QTCORENAME > /dev/null; then
        echo "Qt seems OK."
    else
        if [ $MACOS ]; then
            QTCORE=`Controller/check_path.pl -q /Library/Frameworks/QtCore.framework QtCore`
        fi

        if [ ! $QTCORE ]; then
            echo "Haven't found Qt."
            echo "[c]ontinue without Qt-support"
            echo "[i]nput your own path to QtCore"
            echo "[f]ind it with the unix find command (could take a while)"
            read answer
            if [ $answer = 'i' ]; then
                echo "Enter path to the directory containing $QTCORENAME:"
                read inpath
                QTCORE=`Controller/check_path.pl -q $inpath $QTCORENAME`
            elif [ $answer = 'f' ]; then
                ARRAY=(`find / -name "$QTCORENAME" -print 2>/dev/null`)
                if [ ${#ARRAY[@]} -ge 1 ]; then
                    selection=0;
                    if [ ${#ARRAY[@]} -gt 1 ]; then
                        echo "Found the following locations for $QTCORENAME:"
                        i=0;
                        while [ $i -lt ${#ARRAY[@]} ]; do
                            echo "$i: ${ARRAY[$i]}"
                            i=$[$i+1];
                        done
                        echo "Which one should I use? [default 0]:"
                        read selection
                        if [ ! $selection ]; then selection=0; fi
                    fi
                    QTCORE=`dirname ${ARRAY[$selection]}`
                fi
            fi
            if [ ! $QTCORE ]; then
                unset WITHQT
                echo "Qt not found, continuing without."
            fi
        fi
        if [ $WITHQT ]; then
            if [ $MACOS ]; then
                QTHOME=`dirname $QTCORE`
#                echo "QTHOME = $QTHOME"
                if Controller/check_path.pl -q ${QTHOME}/QtNetwork.framework QtNetwork > /dev/null && Controller/check_path.pl -q ${QTHOME}/QtGui.framework QtGui > /dev/null && Controller/check_path.pl -q ${QTHOME}/QtXml.framework QtXml > /dev/null &&
                Controller/check_path.pl -q ${QTHOME}/QtOpenGL.framework QtOpenGL > /dev/null && Controller/check_path.pl -q ${QTHOME}/QtSql.framework QtSql > /dev/null
                    then
                    echo "Qt settings made."
                else
                    echo "Qt installation incomplete. Continuing without Qt support."
                    unset WITHQT
                fi
            else
                if Controller/check_path.pl -q $QTCORE libQtNetwork.so libQtGui.so libQtXml.so libQtOpenGL.so libQtSql.so; then
                    echo "Qt settings made."
                else
                    echo "Qt installation incomplete. Continuing without Qt support."
                    unset WITHQT
                fi
            fi
        else
            echo "No Qt support."
        fi
        if [ $WITHQT ]; then
            echo "# for Qt" >> $TMPFILE
            if [ $MACOS ]; then
                echo "export Qt_home=$QTHOME" >> $TMPFILE
                echo "export DYLD_LIBRARY_PATH=\$Qt_home/QtNetwork.framework:\$Qt_home/QtGui.framework:\$Qt_home/QtOpenGL.framework:\$Qt_home/QtSql.framework:\$Qt_home/QtXml.framework:\$Qt_home/QtCore.framework:\$DYLD_LIBRARY_PATH" >> $TMPFILE
            else
                echo "export LD_LIBRARY_PATH=$QTCORE:\$LD_LIBRARY_PATH" >> $TMPFILE
            fi
            echo >> $TMPFILE
        fi
    fi
else
   echo "Selected no Qt."
fi

# OpenScientist settings
if [ $WITHOSC ]; then
    if osc-config --version; then
        echo "OpenScientist is already set up."
    else
        echo "Enter path to OpenScientist (e.g. /home/lars/packages/osc_vis/16.11)"
        echo "If you leave this empty, I will try to use find (could take a while)"
        read OSCPATH
        if [ ! $OSCPATH ]; then
            ONXLIBNAME="libOnXLabAIDA$LIBSUFFIX"
            ARRAY=(`find / -name "$ONXLIBNAME" -print 2>/dev/null`)
            if [ ${#ARRAY[@]} -ge 1 ]; then
                selection=0;
                if [ ${#ARRAY[@]} -gt 1 ]; then
                    echo "Found the following locations for OpenScientist:"
                    i=0;
                    while [ $i -lt ${#ARRAY[@]} ]; do
                        entry=`dirname ${ARRAY[$i]}`
                        if [ -d $entry ]; then
                            entry=`dirname $entry`
                            echo "$i: $entry"
                        fi
                        i=$[$i+1];
                    done
                    echo "Which one should I use? [default 0]:"
                    read selection
                    if [ ! $selection ]; then selection=0; fi
                fi
                OSCPATH=`dirname ${ARRAY[$selection]}`
                OSCPATH=`dirname $OSCPATH`
            else
                echo "Couldn't find OpenScientist. Continuing without OpenScientist support."
                unset WITHOSC
            fi
        fi
        
        if [ $OSCPATH ]; then
            if grep "OSC_home=\"@@absolute_dir@@\"" $OSCPATH/setup.sh ; then
                cd $OSCPATH
                ./install
                cd -
            fi
            echo "# OpenScientist settings" >> $TMPFILE
            echo "source $OSCPATH/setup.sh" >> $TMPFILE
            echo "export ONXLAB_PLOTTER_ROOT=\$PLF_BASE/GUIs" >> $TMPFILE
            echo "export ONXLAB_PLOTTER=\$ONXLAB_PLOTTER_ROOT/BasicPlotter.onx" >> $TMPFILE
            if [ $WITHQT ]; then echo "export ONX_ARGS=-qt" >> $TMPFILE; fi
            if [ $MACOS ]; then echo "export DYLD_LIBRARY_PATH=\$PLF_BASE/DLDs:\$DYLD_LIBRARY_PATH" >> $TMPFILE
            else echo "export LD_LIBRARY_PATH=\$PLF_BASE/DLDs:\$LD_LIBRARY_PATH" >> $TMPFILE; fi
            echo >> $TMPFILE
        fi
    fi
fi

echo "### End of PluginFlow modifications" >> $TMPFILE

echo "Finished."
echo "Should I add the needed lines to .$RCFILE [a]utomatically or do you want [m]anual control? [A/m]"
read answer

if [ ! $answer ] || ([ !$answer = "m" ] && [ !$answer = "M" ]); then
    if [ -f $HOME/.$RCFILE ]; then cp -i $HOME/.$RCFILE $RCFILE.bak; fi
    cat $TMPFILE >> $HOME/.$RCFILE
    echo "Modified .$RCFILE."
    echo "The unmodified version is backed up in '$RCFILE.bak'"
    source $HOME/.$RCFILE
    echo "If you start a new shell you should now be able to run flowshell. Without arguments you should see a stream of random numbers."
    if [ $WITHOSC ]; then echo "'flowshell -i -t -p OnXLabLoadAIDA -f $PLF_BASE/Aida/simplehisto.pflow' should open an OpenScientist window and start filling histograms. (You may have to select the histograms in order to see them.)"; fi
else
    mv $TMPFILE ${RCFILE}_modifications
    echo "The recommended changes have been saved to '${RCFILE}_modifications'."
    echo "Add these lines to your .$RCFILE."
fi

echo "Goodbye."
