#!/bin/sh
#--------------------------------------
# fcitx-config
#

# from xdg-open

detectDE()
{
    if [ x"$KDE_FULL_SESSION" = x"true" ]; then DE=kde;
    elif [ x"$GNOME_DESKTOP_SESSION_ID" != x"" ]; then DE=gnome;
    elif `dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetNameOwner string:org.gnome.SessionManager > /dev/null 2>&1` ; then DE=gnome;
    elif xprop -root _DT_SAVE_MODE 2> /dev/null | grep ' = \"xfce4\"$' >/dev/null 2>&1; then DE=xfce;
    fi
}

run_kde()
{
    command=`which kcmshell4 2>&1`
    haskde=0
    if [ $? -eq 0 ]; then
        checkinstalled=`$command --list | grep -c kcm_fcitx`
        if [ "x$checkinstalled" != "x0" ]; then
            haskde=1
        fi
    fi

    if [ $haskde = "1" ]; then
        if [ x"$1" != x ]; then
            exec $command kcm_fcitx --args $1
        else
            exec $command kcm_fcitx
        fi
    else
        run_gtk $1
    fi
}

run_gtk()
{
    command=`which fcitx-config-gtk 2>&1`
    if [ $? -eq 0 ]; then
        exec $command
    else
        run_xdg
    fi
}

run_gtk3()
{
    command=`which fcitx-config-gtk3 2>&1`
    if [ $? -eq 0 ]; then
        exec $command $1
    else
        run_gtk $1
    fi
}

run_xdg()
{
    command=`which xdg-open`
    if [ $? -eq 0 ]; then
        if [ x"$1" != x ]; then
            exec $command "$HOME/.config/fcitx/conf/$1.config"
        else
            exec $command "$HOME/.config/fcitx/config"
        fi
    else
        exit 0
    fi
}

if [ ! -n "$DISPLAY" ]; then
    [ -n "$EDITOR" ] && which $EDITOR > /dev/null 2>&1 && exec $EDITOR $HOME/.config/fcitx/config
    [ -n "$VISUAL" ] && which $VISUAL > /dev/null 2>&1 && exec $VISUAL $HOME/.config/fcitx/config
    echo 'Please run it under X, or set $EDITOR or $VISUAL'
    exit 0
fi

detectDE

case "$DE" in
    kde)
        run_kde $1
        ;;
    *)
        run_gtk3 $1
        ;;
esac
