#!/bin/bash

#
# This script is part of the KGtk package.
#
# (C) Craig Drummond, 2007
#
# Craig.Drummond@lycos.co.uk
#
# --
# Released under the GPL v2 or later
# --
#
# This script attempts to determine which KGtk library (if any) should
# be used when launching the app
#

if [ "`locale | grep 'LANG=' | grep -i 'utf-8' | wc -l`" = "0" ] ; then
    export G_BROKEN_FILENAMES=1
fi

app=`basename $0`
useApp=1

if [ "$app" = "kgtk-wrapper" ] ; then
    app=`basename $1`
    useApp=0
fi

dir=$(cd "$(dirname "$0")"; pwd)
if [ $useApp -eq 1 ] ; then
    oldPath=$PATH
    PATH=`echo $PATH | sed s:$dir::g | sed "s|::*|:|g"`
fi

realApp=`which $app`

if [ -z $realApp ] ; then
    realApp=`which ./$app`
fi

if [ $useApp -eq 1 ] ; then
   PATH=$oldPath
fi

toolkit=`kreadconfig --file kgtkrc --group 'Apps' --key "$app"`

if [ "$toolkit" = "" ] ; then
    case $app in
        eclipse | gimp | inkscape | firefox | kino | iceweasel | swiftfox | azureus | mozilla* )
            toolkit="gtk2" ;;
        scribus | scribus-ng | opera | designer-qt3 )
            toolkit="qt3" ;;
        designer-qt4 )
            toolkit="qt4" ;;
        abiword) # Non-working
            toolkit="x" ;;
    esac
fi

if [ "$toolkit" = "" ] && [ ! -z "$realApp" ] ; then
    libs=`ldd $realApp 2>/dev/null`

    if [ ! -z "$libs" ] ; then

        if [ "0" != "`echo $libs | grep libgtk-x11-2 | wc -l`" ] ; then
            toolkit="gtk2"
        elif [ "0" != "`echo $libs | grep libtqt-mt | wc -l`" ] ; then
            toolkit="qt3"
        elif [ "0" != "`echo $libs | grep libQtGui | wc -l`" ] ; then
            toolkit="qt4"
        fi

        if [ "$toolkit" = "qt3" ] || [ "$toolkit" = "qt4" ] ; then
            if [ "0" != "`echo $libs | grep libtdeio | wc -l`" ] ; then
                toolkit=""
            fi
        fi

        if [ -z "`which k$toolkit-wrapper`" ] ; then
            toolkit=""
        fi
    fi
fi

if [ "$toolkit" = "x" ] ; then
    toolkit=""
fi

if [ $useApp -eq 1 ] ; then
    if [ "$toolkit" = "" ] ; then
        $realApp "$@"
    else
        k$toolkit-wrapper $realApp "$@"
    fi
else
    if [ "$toolkit" = "" ] ; then
        "$@"
    else
        k$toolkit-wrapper "$@"
    fi
fi

