#!/bin/sh

## 1065-refracta-lang - Additional Configuration Script for Debian Live
## 
## Version: 20170304
##
## Script goes in /lib/live/config/ (or other alternative, see <man live-config>)
## Best installed as a deb package
## 
## Automatically select language and keyboard from (boot prompt) cmdline
## 
## Usage examples: components=refracta-lang lang=de_DE || components=refracta-lang lang=en_GB
## Where both parts of a locale are the same, e.g. de_DE fr_FR it should work with just lang=de
## 
## This script will exit if "locales=" (official live-config parameter) was used
## 
## There is no need to additionally use "components=keyboard-configuration keyboard-layouts=whatever"
## UNLESS a keyboard different from the system locale is required
## 
## This script does not support keyboard variants nor non-UTF-8 locales.
## 
## For Debian/Devuan Jessie
## This script must run after user-setup, after locales and before login
##
## Copyright (C) 2013-2017 David Hare <dzz@exegnulinux.net>
## Copyright (C) 2006-2014 Daniel Baumann <mail@daniel-baumann.ch> (original live-config)
## Copyright (C) 2014 Vladimir Kudrya <pzs-fs@yandex.ru> (lightdm-locale-fix)
## 
## Licence: GPL3

# ### Uncomment the next line to get a full debug log ###
# exec 2>"/var/log/live/1065-refracta-lang.log" && set -x
	

Init ()
{
	# exit if this script is already configured
	if [ -e /var/lib/live/config/refracta-lang ]; then
		exit 0
	fi

	# exit if "locales=" (official live-config parameter) was specified
	if (cat /proc/cmdline|grep -q " locales="); then
		fix_lightdm
		exit 0
	fi

	# exit if "lang=" was *not* specified
	if ! (cat /proc/cmdline|grep -q " lang="); then
		exit 0
	fi


	echo -n " refracta-lang "
}


configure_locales ()
{
	# Identify what "lang=" was specified on cmdline (and remove ".UTF-8" if used)
	LANG_SELECTED="$(cat /proc/cmdline|grep -o "lang=.*" | sed "s/ .*//"| sed "s/\..*//"| sed "s/lang=//")"

	# if $LANG_SELECTED is (e.g.) simply "es", make it es_ES
	if (echo "${LANG_SELECTED}" | grep -sqE '^[[:lower:]]{2}$'); then
		LANG_SELECTED_UP=$(echo "${LANG_SELECTED}" | tr '[a-z]' '[A-Z]')
		LANG_SELECTED="${LANG_SELECTED}_${LANG_SELECTED_UP}"
	fi

	# Check if selection is supported, else fallback to en_US)
	LOCALE_SUPPORTED="$(cat /usr/share/i18n/SUPPORTED|grep UTF-8|grep ${LANG_SELECTED}|awk '{print $1}')"

	if [ -n  "${LOCALE_SUPPORTED}"} ]; then
		LOCALE_SELECTED="${LOCALE_SUPPORTED}"
		# now $LOCALE_SELECTED is formatted e.g. "de_DE.UTF-8", leave it like that
	else
		echo " locale ${LOCALE_SELECTED} is unsupported (or input error)."
		# fallback to default
		LOCALE_SELECTED="en_US.UTF-8"
	fi

	# Generate selected locale if necessary.
	if ! (grep -q "^${LOCALE_SELECTED}" /etc/locale.gen); then
		sed -i -e "s/# ${LOCALE_SELECTED}/${LOCALE_SELECTED}/" /etc/locale.gen
		locale-gen --keep-existing
	fi

	# Set the console keyboard
	echo "LANG=${LOCALE_SELECTED}" > /etc/default/locale

	# Get live username. Overwrite ~/.dmrc with no set locale. Display manager will do the rest.
	USER_1000=$(id -nu 1000)

	echo -e "\n[Desktop]\nSession=default" >/home/${USER_1000}/.dmrc
	chown 1000:1000 /home/${USER_1000}/.dmrc
}


configure_console_keyboard ()
{
	if (cat /proc/cmdline|grep -q " keyboard-layouts="); then

		# The keyboard was set by keyboard-layouts, use that. Console keyboard is already configured.
		LAYOUTS="$(cat /proc/cmdline|grep -o "keyboard-layouts=.*" | sed "s/ .*//" | sed "s/keyboard-layouts=//")"
	else
		# Set $LAYOUTS from lang=something (same as locale)
		# e.g. lang=de_DE. If e.g. only "lang=de" was specified, done like this it still works!
		LAYOUTS="$(echo ${LOCALE_SELECTED}|sed "s/.UTF-8//"|sed "s/[a-z][a-z]_//" |tr '[A-Z][A-Z]' '[a-z][a-z]')"

		### Set the console keyboard (adapted from official "keyboard-configuration" script):

		sed -i -e "s|^XKBLAYOUT=.*$|XKBLAYOUT=\"${LAYOUTS}\"|" /etc/default/keyboard
		echo "keyboard-configuration keyboard-configuration/layoutcode select ${LAYOUTS}" >> /tmp/debconf.live

		# uncomment if wanted:
		# sed -i "s/XKBOPTIONS=.*/XKBOPTIONS=\"terminate:ctrl_alt_bksp\"/" /etc/default/keyboard

			if [ -e /tmp/debconf.live ]; then
				debconf-set-selections < /tmp/debconf.live
				rm -f /tmp/debconf.live
			fi
	fi
}


configure_xfce_keyboard ()
{
	if ! (ls /home/${USER_1000}/.config/xfce4/panel|grep -q xkb-plugin); then
		return # No xfce4 panel switcher to edit
	fi

	#  For the panel keyboard switcher, Set some preset alts from a "most-common" shortlist .
	#  Remove the user choice (and leading or trailing commas) from the list.
	KB_ALT=$(echo "us,gb,de,fr,es,nl,pt,it" |sed "s/${LAYOUTS},//"|sed "s/,${LAYOUTS}//")

	# Set the  user choice first then 3 (max supported for xfce switcher) alts
	XLAYOUTS="$(echo ${LAYOUTS},${KB_ALT}|awk -F , '{print $1","$2","$3","$4}')"

	# There could be more than one xkb-plugin file.
	for i in $( ls /home/${USER_1000}/.config/xfce4/panel|grep xkb-plugin ); do
		sed -i "s/layouts=.*/layouts=${XLAYOUTS}/" /home/${USER_1000}/.config/xfce4/panel/${i};
	done

	# This file may override what we just did, if it's set differently.
	rm -f home/${USER_1000}/.config/xfce4/xfconf/xfce-perchannel-xml/keyboard-layout.xml

	# sort permissions for user files
	chown -R 1000:1000 /home/${USER_1000}/.config/xfce4/panel
}


fix_lightdm ()
{
	if ! [ -f "/var/lib/dpkg/info/lightdm.list" ]; then
		return
	fi

cat <<'EOF' >/etc/X11/Xsession.d/21-lightdm-locale-fix

# workaround for lightdm session language selection bug
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=765077

if pidof lightdm
then
	# use Language setting from ~/.dmrc
	export LANG=`cat "$HOME/.dmrc" | grep '^Language=' | cut -d '=' -f 2- | sed 's/utf8/UTF-8/'`

	# if $LANGUAGE is set, sync it with chosen locale
	[ -n "$LANGUAGE" ] && export LANGUAGE=`echo $LANG | cut -d '.' -f 1`:`echo -n $LANG | cut -d '.' -f 1 | cut -d '_' -f 1`

	# remove untrustworthy $GDM_LANG
	[ -n "$GDM_LANG" ] && unset GDM_LANG
fi

EOF
	# TODO .. sort the right permission
	chmod 644 /etc/X11/Xsession.d/21-lightdm-locale-fix
	#chmod 755 /etc/X11/Xsession.d/21-lightdm-locale-fix
}


# run each function
Init
configure_locales
configure_console_keyboard
configure_xfce_keyboard
fix_lightdm

# Creating state file
touch /var/lib/live/config/refracta-lang
