#!/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)" != "wily" ]; 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

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

LAYOUT_CODE=$(echo 'get keyboard-configuration/layoutcode' | debconf-communicate 2>/dev/null)
INPUT_SOURCE=$(gsettings get org.gnome.desktop.input-sources sources)
NEW_SOURCE=""
if [ "${INPUT_SOURCE}" = "[('xkb', 'jp'), ('xkb', 'us'), ('ibus', 'anthy')]" ] ||
   [ "${INPUT_SOURCE}" = "@a(ss) []" ] ; then
	if [ "${LAYOUT_CODE}" = "0 jp" ]; then 
		NEW_SOURCE="[('xkb', 'jp'), ('fcitx', 'mozc')]"
	elif [ "${LAYOUT_CODE}" = "0 us" ] ; then
		NEW_SOURCE="[('xkb', 'us'), ('fcitx', 'mozc')]"
	fi
elif [ "${INPUT_SOURCE}" = "[('xkb', 'jp')]" ] ||
     [ "${INPUT_SOURCE}" = "[('xkb', 'jp'), ('ibus', 'anthy')]" ] ||
     [ "${INPUT_SOURCE}" = "[('xkb', 'jp'), ('fcitx', 'mozc'), ('xkb', 'jp+OADG109A'), ('xkb', 'jp+dvorak'), ('xkb', 'nec_vndr/jp')]" ]; then
	NEW_SOURCE="[('xkb', 'jp'), ('fcitx', 'mozc')]"
elif [ "${INPUT_SOURCE}" = "[('xkb', 'us')]" ] ||
     [ "${INPUT_SOURCE}" = "[('xkb', 'us'), ('ibus', 'anthy')]" ]; then
	NEW_SOURCE="[('xkb', 'us'), ('fcitx', 'mozc')]"
fi

[ -z "$NEW_SOURCE" ] && exit

CONDITION=1
for i in {0..9}
do
	gsettings set org.gnome.desktop.input-sources sources "${NEW_SOURCE}"
	if [ "$(gsettings get org.gnome.desktop.input-sources sources)" = "${NEW_SOURCE}" ]; then
		CONDITION=0
		break
	fi
	sleep 1
done

if [ $CONDITION -ne 0 ]; then
	exit
fi

if [ -e ${CONFIGDIR} ]; then
	[ ! -d ${CONFIGDIR} ] && exit
else
	mkdir ${CONFIGDIR}
fi
echo "${LAYOUT_CODE}" > ${CONFIGFILE}
echo "${INPUT_SOURCE}" >> ${CONFIGFILE}
echo "${NEW_SOURCE}" >> ${CONFIGFILE}
