#!/bin/sh
PIDFILE=/var/run/espeakup.pid

. /usr/share/debconf/confmodule

set -e

locale="$1"

[ -f $PIDFILE ] || exit 0

lang=`echo $locale | sed 's/_.*//'`
country=`echo $locale | sed 's/.*_//;s/\..*//;s/@.*//' | tr A-Z a-z`

# Not supported by espeak yet, but should be fine enough, better than english
# anyway. Note: update LANG_APPROX in debian/rules as well
case $lang in
	ast) lang=es ;;
	gl) lang=pt ;;
	nn) lang=nb ;;
	oc) lang=ca ;;
	se) lang=fi ;;
	tg) lang=fa ;;
esac

# Mbrola codes :/
# List from espeak-ng-data/voices/mb
case ${lang}_${country} in
	# af
	# ar
	pt_BR) MB_VOICE=br ;;
	fr_CA) MB_VOICE=ca ;;
	zh_*) MB_VOICE=cn ;;
	# cr
	cs_*) MB_VOICE=cz ;;
	# de
	et_*) MB_VOICE=ee ;;
	# en
	# es
	# fr
	el_*) MB_VOICE=gr ;;
	he_*) MB_VOICE=hb ;;
	# hu
	is_*) MB_VOICE=ic ;;
	# id
	hi_*) MB_VOICE=in ;;
	fa_*) MB_VOICE=ir ;;
	# it
	ja_*) MB_VOICE=jp ;;
	# la
	# lt
	ms_*) MB_VOICE=ma ;;
	es_MX) MB_VOICE=mx ;;
	# nl
	mi_*) MB_VOICE=nz ;;
	# pl
	# pt
	# ro
	sv_*) MB_VOICE=sw ;;
	te_*) MB_VOICE=tl ;;
	# tr
	en_US) MB_VOICE=us ;;
	es_VE) MB_VOICE=vz ;;
	*) MB_VOICE=$lang ;;
esac

mbrola_voice=$(ls /usr/share/mbrola/${MB_VOICE}[1-9]/${MB_VOICE}[1-9] 2> /dev/null | head -n 1)

if [ -n "$mbrola_voice" ]
then
	default_voice=mb-$(basename $mbrola_voice)
elif grep -r "^language $lang-$country$" /usr/lib/*/espeak-ng-data/lang
then
	default_voice="$lang-$country"
elif grep -r "^language $lang$" /usr/lib/*/espeak-ng-data/lang
then
	default_voice="$lang"
else
	default_voice=en
fi

db_set espeakup/voice $default_voice
CARD=$(cat /var/run/espeakup.card)
[ -n "$CARD" ] || CARD=0
export ALSA_CARD=$(cat /sys/class/sound/card$CARD/id)
db_set espeakup/card "$ALSA_CARD"

[ $lang = en ] || echo 1 > /sys/accessibility/speakup/soft/direct

# Trigger an espeakup restart
echo $default_voice > /var/run/espeakup.voice
touch -r $PIDFILE $PIDFILE.old
sleep 2 # Make sure we can distinguish the pid files
kill `cat $PIDFILE`
while [ ! $PIDFILE.old -ot $PIDFILE ]; do sleep 1 ; done
