#!/bin/bash

#Fcitx Setup Helper
#Copyright 2015 AWASHIRO Ikuya <ikuya@fruitsbasket.info>
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

CONFIGDIR="${HOME}/.config/fcitx-setup-helper"
CONFIGFILE="${CONFIGDIR}/run"

if [ "$(lsb_release -cs)" != "vivid" ]; then
        exit
fi

if [ "${GTK_IM_MODULE}" != "fcitx" ]; then
        exit
fi

if [ -e "${CONFIGFILE}" ]; then
	exit
fi

if [ -z "$(echo ${XDG_CURRENT_DESKTOP}|grep Unity)" ]; then
	exit
fi

for i in fcitx fcitx-mozc fcitx-anthy
do
	if [ "$(dpkg-query -W $i|cut -f1|sed s/:.*//g)" != "$i" ]; then
		exit
	fi
done

#TODO: 日本語でも英語でもないキーボードが指定された場合の対応
INPUT_SOURCE=$(gsettings get org.gnome.desktop.input-sources sources)
if [ "${INPUT_SOURCE}" = "[('xkb', 'jp'), ('xkb', 'us'), ('ibus', 'anthy')]" ] || [ "${INPUT_SOURCE}" = "[('xkb', 'jp'), ('ibus', 'anthy')]" ]; then
	if [ "$(dpkg-query -W fcitx-kkc|cut -f1|sed s/:.*//g)" = "fcitx-kkc" ]; then
        	gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'jp'), ('fcitx', 'mozc'), ('fcitx', 'kkc'), ('fcitx', 'anthy')]"
	else
        	gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'jp'), ('fcitx', 'mozc'), ('fcitx', 'anthy')]"
	fi
elif [ "${INPUT_SOURCE}" = "[('xkb', 'us'), ('ibus', 'anthy')]" ] ; then
	if [ "$(dpkg-query -W fcitx-kkc|cut -f1|sed s/:.*//g)" = "fcitx-kkc" ]; then
        	gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'us'), ('fcitx', 'mozc'), ('fcitx', 'kkc'), ('fcitx', 'anthy')]"
	else
        	gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'us'), ('fcitx', 'mozc'), ('fcitx', 'anthy')]"
	fi
else
	exit
fi

if [ -d "${CONFIGDIR}" ]; then
	touch ${CONFIGFILE}
else
	mkdir ${CONFIGDIR}
	touch ${CONFIGFILE}
fi
