ibus_panel=$(im-settings config --get ibus.panel)
optargs=""
kimpanels="
/usr/lib64/libexec/kimpanel-ibus-panel
/usr/lib/libexec/kimpanel-ibus-panel
/usr/lib64/kde4/libexec/kimpanel-ibus-panel
/usr/lib/kde4/libexec/kimpanel-ibus-panel"

find_kimpanel_panel() {
   for panel in $kimpanels; do
      if [ -e $panel ]; then
         echo $panel
         return
      fi
   done
}

if [ "$XDG_CURRENT_DESKTOP" = "GNOME" ]; then
   # TODO: if the engine list is empty, add default engines for the current locale

   # IBus is launched by GNOME Shell
   echo "IM: IBus will be launched by GNOME Shell. Exiting..." 1>&2
   exit 0;
fi

if [ "$ibus_panel" != "" ]; then
   optargs="--panel=$ibus_panel"
   echo "IM: ibus panel is specified." 1>&2
else
   kimpanel=`find_kimpanel_panel`
   if [ $kimpanel != "" ]; then
      # wait until kimpanel become active
      sleep 10

      type dbus-send > /dev/null && \
      dbus-send --dest=org.freedesktop.DBus --print-reply=literal /org/freedesktop/DBus org.freedesktop.DBus.ListNames | grep org.kde.impanel > /dev/null

      if [ "$?" = "0" ]; then
         echo "IM: Use $kimpanel instead of ibus-ui-gtk3" 1>&2
         optargs="--panel=$kimpanel"
      fi
   fi
fi

echo "IM: Additional args to ibus-daemon: \"$optargs\"" 1>&2
ibus-daemon -d -x $optargs
