#!/bin/bash

function Usage()
{
    echo -e "$0 - Fcitx Fbterm launch helper"
    echo -e "\t-l\t\tLaunch Fcitx automatically"
    echo -e "\t-h\t\tPrint this help"
}

LAUNCH=0
FCITX_RUN=0

while getopts "lh" opt; do
    case $opt in
        l)
            LAUNCH=1
            ;;
        *)
            Usage
            exit 0
            ;;
    esac
done

if [ "x$DISPLAY" != "x" ]; then
    number=`echo $DISPLAY | sed 's|\:\([0-9]\+\)\(\..*\)\?|\1|g'`
    if [ "x$number" == "x" ]; then
        echo '$DISPLAY parse error'
        exit 1
    fi
    echo "Your display number is $number"
else
    number=0
fi

echo "Test whether fcitx is running correctly with dbus..."
dbus-send --print-reply --type=method_call --session --dest=org.fcitx.Fcitx-$number /inputmethod org.freedesktop.DBus.Introspectable.Introspect > /dev/null 2>&1

if [ $? == "1" ]; then
    echo "Cannot communicate fcitx with DBus."
    FCITX_RUN=0
else
    echo "Fcitx is running correctly."
    FCITX_RUN=1
fi
    
echo ''
echo '========================================================='

if [ "$FCITX_RUN" == "0" -a "$LAUNCH" == "1" ]; then
    echo "Try launch fcitx..."
    pgrep -u `whoami` '^fcitx$' > /dev/null 2>&1
    if [ $? == "0" ]; then
        echo "There is already a fcitx running, Fcitx cannot support multi instance currently"
        exit 1
    fi
    if [ "x$DISPLAY" != "x" ]; then
        echo '$DISPLAY is set, but there is no fcitx running.'
        echo "You'd better start it from X."
        exit 1
    fi
    if test -z "$DBUS_SESSION_BUS_ADDRESS" ; then
        echo "Launch DBus..."
        toeval=`dbus-launch --sh-syntax`
        eval "$toeval"
    fi
    echo "Launch Fcitx..."
    fcitx > /dev/null 2>&1
    FCITX_RUN=1
fi

if [ $FCITX_RUN == "1" ]; then
    echo "Launch fbterm..."
    fbterm -i fcitx-fbterm
    if [ "$LAUNCH" == "1" ] ; then
        fcitxpid=`dbus-send --print-reply --type=method_call --session --dest=org.freedesktop.DBus / org.freedesktop.DBus.GetConnectionUnixProcessID string:org.fcitx.Fcitx-0 | grep uint32 | awk '{print $2}'`
        if ! test -z "$fcitxpid" ; then
            kill $fcitxpid
        fi
        if ! test -z "$DBUS_SESSION_BUS_PID"; then
            kill $DBUS_SESSION_BUS_PID
        fi
    fi
else
    echo '========================================================='
    echo 'Fcitx is not running, you may setup it mannually'
    echo 'The easiest way is set $DISPLAY, start fcitx from X'
    echo 'Then try this helper'
    echo '========================================================='
fi
