#!/bin/sh

#     Copyright © 2005 Anton Zinoviev <anton@lml.bas.bg>

#     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 2 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.

#     If you have not received a copy of the GNU General Public License
#     along with this program, write to the Free Software Foundation, Inc.,
#     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#                        ----------
#                         CONTENTS
#                        ----------
#
# 1. Define the function all_kbdnames that list all supported keyboard
#    models, layouts and variants.
#
# 2. Function ask_debconf.  Ask user to choose amongst the options
#    listed in $kbdnames.
#
# 3. Function guess_arch - detect the architecture and subarchitecture
#
# 4. Function keyboard_present - test if the computer has at least one keyboard
#
# 5. Set $locale.  Extract the strings for the chosen language in $kbdnames.
#
# 6. Compute default values for $XKBMODEL, $XKBLAYOUT, $XKBVARIANT
#    based on the architecture and the locale.
#
# 7. Overwrite (some of) the computed default values by:
#    - preseeded values (for the udeb);
#    - the value of debian-installer/keymap
#    - the contents of /etc/X11/xorg.conf
#    - the settings in the configuration files (/etc/default/...).
#
# 8. Compute default values for the Debconf questions.  For example
#    XKBOPTIONS=lv3:ralt_switch gives default_altgr='Right Alt (AltGr)'.
#
# 9. If the computer doesn't have keyboard then do not ask questions,
#    simply store the default values in the configuration file.  This
#    is in order to support headless installs in d-i.  The regular
#    packages (console-setup and console-setup-mini) should not be
#    installed on such sistems.
#
# 10. Ask the Debconf questions starting from STATE=1.
#
# 11. Fix the model of the Brazilian and Japanese keyboards.

set -e

. /usr/share/debconf/confmodule

CONFIGFILE=/etc/default/keyboard
OLDCONFIGFILE=/etc/default/console-setup

default_toggle=''
default_switch=''
default_altgr=''
default_compose=''
default_layout=''
default_variant=''
XKBMODEL=''
XKBLAYOUT=''
XKBVARIANT=''
XKBOPTIONS=''

if [ -f /usr/share/console-setup/keyboard-configuration.config ]; then
    is_debian_installer=yes
    is_not_debian_installer=''
else
    is_debian_installer=''
    is_not_debian_installer=yes
fi

## KBDNAMES ## Will be replaced by all_kbdnames function:

# all_kbdnames () {
#  cat <<'EOF' 
# C*model*logidinovo*Logitech diNovo Keyboard
# C*model*amiga*Amiga
# ...
# zh_TW*layout*al*阿爾巴尼亞
# zh_TW*variant*al**阿爾巴尼亞
# EOF
# }

db_capb backup

# Store default value into debconf db.  Workaround #352697.
db_default () {
    db_get keyboard-configuration/store_defaults_in_debconf_db
    if [ "$RET" = true ]; then
	db_set $1 "$2"
    fi
}

regex_escape () {
    sed \
	-e 's/[.]/%period%/g' \
	-e 's/\[/%lbracket%/g' \
	-e 's/\]/%rbracket%/g' \
	-e 's/\^/%caret%/g' \
	-e 's/\$/%dollar%/g' \
	-e 's/\\/%bslash%/g' \
	-e 's/[/]/%slash%/g' \
	-e 's/[?]/%question%/g' \
	-e 's/[+]/%plus%/g'
}

regex_pattern_escape () {
    sed \
	-e 's/[.]/%period%/g' \
	-e 's/\[/%lbracket%/g' \
	-e 's/\]/%rbracket%/g' \
	-e 's/\^/%caret%/g' \
	-e 's/\$/%dollar%/g' \
	-e 's/\\/%bslash%/g' \
	-e 's/[/]/%slash%/g' \
	-e 's/[?]/%question%/g' \
	-e 's/[+]/%plus%/g' \
	-e 's/[*]/\\*/g'
}

regex_unescape () {
    sed \
	-e 's/%period%/./g' \
	-e 's/%lbracket%/[/g' \
	-e 's/%rbracket%/]/g' \
	-e 's/%caret%/^/g' \
	-e 's/%dollar%/$/g' \
	-e 's/%bslash%/\\/g' \
	-e 's/%slash%/\//g' \
	-e 's/%question%/?/g' \
	-e 's/%plus%/+/g'
}

# A high level function to ask questions about the keyboard model,
# layout and variant
ask_debconf () {
    local template priority prefix default_code default_description choices add

    # The template to ask
    template="$1"
    # The priority for the question
    priority="$2"
    # The prefix for $kbdnames
    prefix="$(echo "$3"|regex_pattern_escape)"
    # The default choice (optional)
    default_code="$(echo "$4"|regex_pattern_escape)"
    # Additional string to append to $kbdnames
    add="$(echo "$5"|regex_escape)"
    add="
$add"

    choices1=`echo "$kbdnames" | grep "^$prefix\*" | 
        sed -e "s/^$prefix\*[^\*]*\*//" -e 's/,/\\\\,/g' | sort`
    choices2=`echo "$add" | grep "^$prefix\*" | 
        sed -e "s/^$prefix\*[^\*]*\*//" -e 's/,/\\\\,/g'`
    choices=`echo "$choices1
$choices2" | sed -e 's/$/,/'`
    choices=`echo $choices | sed 's/, *$//' | regex_unescape`

    choices=`echo $choices | sed 's/,$//'`

    if echo "$choices" | grep '[^\\\\],' >/dev/null; then
	db_subst $template CHOICES "$choices"
	default_description=`echo "$kbdnames$add" |  
            grep "^$prefix\*${default_code}\*" |
            sed -e "s/^$prefix\*${default_code}\*//" |
	    regex_unescape`
	if [ -z "$default_description" ]; then
	    # For XkbVariant the empty string is usually a sensible default
	    default_description=`echo "$kbdnames$add" |  
                grep "^$prefix\*\*" |
		sed -e "s/^$prefix\*\*//" |
		regex_unescape `
	fi
	if [ -n "$default_description" ]; then
	    db_default $template "$default_description"
	elif [ -n "$default_code" ]; then
	    # A default was requested, but we couldn't resolve it to a
	    # description, so we'd better ask.
	    priority=critical
	fi
	
        db_input $priority $template || true
	db_go || return 255
	db_get $template
    else
	# There is only one choice - no need to use debconf
	[ $STATE -gt $old_state ] || return 255
	RET=$(echo "$choices"|sed 's/ *$//')
    fi

    RET=`echo "$RET" | regex_pattern_escape`
    RET=`echo "$kbdnames$add" | grep "^$prefix\*[^\*]*\*" |
             sed 's/  */ /g' |
             grep "\*$RET\$" |
             sed -e "s/^$prefix\*\([^\*]*\)\*.*/\1/" |
	     regex_unescape`
    return 0
}

# The guess arch code is taken from "console-data.conf"
# (translated from Perl to shell)

# SUBARCH	KEYMAP SET	DETECTION
# m68k/atari	atari		"Model: Atari"
# m68k/amiga	amiga		"Model: Amiga"
# m68k/mac	mac		"Model: Macintosh"
# m68k/mvme	pc		"Model: Motorola"
# m68k/bvme	pc		"Model: BVME[46]000"
# m68k/{sun,apollo,next,q40,hp300} Not supported by Debian

# ppc/apus	amiga		"machine: Amiga"
# ppc/chrp	pc,mac		"machine: CHRP"
# ppc/pmac	mac		"machine: PowerMac|[Pp]ower[Bb]ook*|Power|iMac*|PowerMac1*"
# ppc/prep	pc		"machine: PReP"
# ppc/ps3	pc		"platform: PS3"
# ppc/cell	pc		"platform: Cell"
# ppc/{bbox,mbx,ppc64,82xx,8xx} Not yet supported by Debian

# arm/*		pc		(refered to as 'arm' only)

guess_arch () {
    local arch subarch line

    if type archdetect 2>/dev/null >/dev/null; then
	archdetect
	return 0
    fi

    arch=`dpkg --print-architecture`
    
    if [ "$arch" = 'powerpc' -o "$arch" = 'm68k' ]; then
	if [ "$arch" = powerpc ]; then
	    line=`sed -n 's/^platform.*: *//p' /proc/cpuinfo`
	    if [ "$line" = PS3 ] || [ "$line" = Cell ]; then
		subarch=`echo $line|tr A-Z a-z`
	    else
		line=`sed -n 's/^machine.*: *//p' /proc/cpuinfo`
		if [ "$line" = '' ]; then
		    echo unknown
		    return 0
		fi
		subarch=`echo $line|tr A-Z a-z`
	    fi
	elif [ "$arch" = m68k ]; then
	    line=`sed -n 's/^Model.*: *//p' /proc/hardware`
	    if [ "$line" = '' ]; then
		echo unknown
		return 0
	    fi
	    subarch=`echo $line|tr A-Z a-z`
	fi
	case "$subarch" in
	    *amiga*)
		subarch=amiga
		;;
	    *chrp*)
		subarch=chrp
		;;
	    *prep*)
		subarch=prep
		;;
	    *macintosh*|*powermac*|*powerbook*|*power*|*imac*|*powermac1*)
		subarch=mac
		;;
	    *atari*)
		subarch=atari
		;;
	    *motorola*)
		subarch=mvme
		;;
	    *bvme*)
		subarch=bvme
		;;
	    *)
		subarch=`echo $subarch|sed  's/^\s*//'`
		;;
	esac
	arch="$arch/$subarch"
    fi
    echo $arch
    return 0
}

## KEYBOARD_PRESENT ## Will be replaced by keyboard_present function

# keyboard_present () {
#     if there is a keyboard; then
# 	return 0
#     else
# 	return 1
#     fi
# }

if type locale 2>/dev/null >/dev/null; then
    eval `locale`
fi

if [ "$LC_CTYPE"  -a "$LC_CTYPE" != C ]; then
    locale=$LC_CTYPE
elif db_get debian-installer/locale && [ "$RET" ]; then
    locale="$RET"
else
    locale=C
fi

if [ "$LC_MESSAGES"  -a "$LC_MESSAGES" != C ]; then
    messages=$LC_MESSAGES
elif db_get debian-installer/locale && [ "$RET" ]; then
    messages="$RET"
else
    messages=C
fi

messages_lang=$(echo $messages | sed 's/_.*//')
messages_country=$(echo $messages | sed 's/.*_//;s/\..*//;s/@.*//')
messages_modif=
echo $messages | grep -v -q @ || messages_modif=$(echo $messages | sed 's/.*@//')

lang_kbdnames () {
    all_kbdnames | \
	regex_escape | \
	grep "^$1[*]" | \
	sed "s/^$1[*]//"
}

kbdnames=$(lang_kbdnames ${messages_lang}_${messages_country}__${messages_modif})
[ -n "$kbdnames" ] || kbdnames=$(lang_kbdnames ${messages_lang}_${messages_country}__${messages_modif})
[ -n "$kbdnames" ] || kbdnames=$(lang_kbdnames ${messages_lang}_${messages_country})
[ -n "$kbdnames" ] || kbdnames=$(lang_kbdnames ${messages_lang})
[ -n "$kbdnames" ] || kbdnames=$(lang_kbdnames C)

! type iconv >/dev/null || \
    kbdnames="$(echo "$kbdnames" |
                iconv -f UTF-8 -t $(locale charmap)//TRANSLIT)"

arch=`guess_arch`

case "$arch" in
    alpha*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    amd64*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    arm*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    i386*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    hppa*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    ia64*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    m68k/amiga)
	XKBMODEL=amiga
	model_priority=medium
	;;
    m68k/atari)
	XKBMODEL=ataritt
	model_priority=medium
	;;
    m68k/mac)
	XKBMODEL=macintosh_old
	model_priority=medium
	;;
    m68k/sun*)
	XKBMODEL=pc105 # UNKNOWN: sun4, sun5 or pc105
	model_priority=critical
	;;
    m68k/*vme*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    mips*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    powerpc/amiga)
	XKBMODEL=amiga
	model_priority=medium
	;;
    powerpc/apus)
	XKBMODEL=amiga
	model_priority=medium
	;;
    powerpc/chrp*)
	XKBMODEL=pc105 # UNKNOWN: pc105, macintosh_old or maybe amiga
	model_priority=critical
	;;
    powerpc/mac)
	XKBMODEL=pc105
	model_priority=medium
	;;
    powerpc/pasemi)
	XKBMODEL=pc105
	model_priority=medium
	;;
    powerpc/powermac*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    powerpc/prep)
	XKBMODEL=pc105
	model_priority=medium
	;;
    powerpc/ps3|powerpc/cell)
	XKBMODEL=pc105
	model_priority=medium
	;;
    sparc*)
	XKBMODEL=pc105 # sun4 or sun5 on older kernels
	model_priority=medium
	;;
    s390*)
	XKBMODEL=pc105
	model_priority=medium
	;;
    *)
	XKBMODEL=pc105 # UNKNOWN
	model_priority=critical
	;;
esac    

layout_priority=critical
case "$locale" in
    # Keyboards for countries
    *_AL*)
	XKBLAYOUT=al  # Albania
	;;
    *_AZ*)
	XKBLAYOUT=az  # Azerbaijan
	;;
    *_BD*)
	XKBLAYOUT=us,bd  # Bangladesh
	;;
    *_BE*)
	XKBLAYOUT=be  # Belgium
	;;
    *_BG*)
	XKBLAYOUT=us,bg  # Bulgaria
	layout_priority=critical
	;;
    *_BR*)
	XKBLAYOUT=br  # Brazil
	;;
    *_BT*)
	XKBLAYOUT=us,bt  # Bhutan
	;;
    *_BY*)
	XKBLAYOUT=us,by  # Belarus
	;;
    fr_CA*)
	XKBLAYOUT=ca  # Canada
	;;
    *_CA*)
	XKBLAYOUT=us  # U.S. English
	;;
    de_CH*)
	XKBLAYOUT=ch  # Switzerland
	;;
    fr_CH*)
	XKBLAYOUT=ch  # Switzerland
	XKBVARIANT=fr # French
	;;
    *_CH*)
	XKBLAYOUT=ch  # Switzerland
	layout_priority=critical
	;;
    *_CZ*)
	XKBLAYOUT=cz  # Czechia
	layout_priority=critical
	;;
    *_DK*)
	XKBLAYOUT=dk  # Denmark
	;;
    *_EE*)
	XKBLAYOUT=ee  # Estonia
	;;
    ast_ES*)
	XKBLAYOUT=es  # Spain
	XKBVARIANT=ast # Asturian
	;;
    ca_ES*)
	XKBLAYOUT=es  # Spain
	XKBVARIANT=cat # Catalan
	;;
    *_ES*)
	XKBLAYOUT=es  # Spain
	;;
    *_ET*)
	XKBLAYOUT=us,et  # Ethiopia
	;;
    se_FI*)
	XKBLAYOUT=fi  # Finland
	XKBVARIANT=smi # Northern Saami
	;;
    *_FI*)
	XKBLAYOUT=fi  # Finland
	;;
    *_FR*)
	XKBLAYOUT=fr  # French
	XKBVARIANT=latin9
	;;
    *_GB*)
	XKBLAYOUT=gb  # United Kingdom
	;;
    *_GG*)
	XKBLAYOUT=gb  # United Kingdom
	;;
    *_HU*)
	XKBLAYOUT=hu  # Hungary
	;;
    *_IE*)
	XKBLAYOUT=ie  # Ireland
	;;
    *_IL*)
	XKBLAYOUT=us,il  # Israel
	layout_priority=critical
	;;
    *_IM*)
	XKBLAYOUT=gb  # United Kingdom
	;;
    *_IR*)
	XKBLAYOUT=us,ir  # Iran
	;;
    *_IS*)
	XKBLAYOUT=is  # Iceland
	;;
    *_IT*)
	XKBLAYOUT=it  # Italy
	;;
    *_JE*)
	XKBLAYOUT=gb  # United Kingdom
	;;
    *_JP*)
	XKBLAYOUT=jp  # Japan
	;;
    *_LT*)
	XKBLAYOUT=lt  # Lithuania
	layout_priority=critical
	;;
    *_LV*)
	XKBLAYOUT=lv  # Latvia
	;;
    *_KG*)
	XKBLAYOUT=us,kg  # Kyrgyzstan
	;;
    *_KH*)
	XKBLAYOUT=us,kh  # Cambodia
	;;
    *_KP*)
	XKBLAYOUT=kr  # Korea
	;;
    *_KZ*)
	XKBLAYOUT=us,kz  # Kazakhstan
	;;
    *_LK*)
	XKBLAYOUT=us,lk  # Sri Lanka
	;;
    *_MA*)
	XKBLAYOUT=us,ma  # Morocco
	;;
    *_MK*)
	XKBLAYOUT=us,mk  # Macedonia
	;;
    *_NL*)
	XKBLAYOUT=us  # Netherlands
	;;
    *_MN*)
	XKBLAYOUT=us,mn  # Mongolia
	;;
    *_MT*)
	XKBLAYOUT=mt  # Malta
	layout_priority=critical
	;;
    se_NO*)
	XKBLAYOUT=no  # Norway
	XKBVARIANT=smi # Northern Saami
	;;
    *_NO*)
	XKBLAYOUT=no  # Norway (se_NO is not in this case)
	;;
    *_NP*)
	XKBLAYOUT=us,np  # Nepal
	;;
    *_PL*)
	XKBLAYOUT=pl  # Poland
	;;
    *_PT*)
	XKBLAYOUT=pt  # Portugal
	;;
    *_RO*)
	XKBLAYOUT=ro  # Romania
	;;
    *_RU*)
	XKBLAYOUT=us,ru  # Russia
	layout_priority=critical
	;;
    se_SE*)
	XKBLAYOUT=se  # Sweden
	XKBVARIANT=smi # Northern Saami
	;;
    *_SK*)
	XKBLAYOUT=sk  # Slovakia
	;;
    *_SI*)
	XKBLAYOUT=si  # Slovenia
	;;
    *_TJ*)
	XKBLAYOUT=us,tj  # Tajikistan
	;;
    *_TH*)
	XKBLAYOUT=us,th  # Thailand
	layout_priority=critical
	;;
    *_TR*)
	XKBLAYOUT=tr  # Turkish
	layout_priority=critical
	;;
    *_UA*)
	XKBLAYOUT=us,ua  # Ukraine
	;;
    en_US*)
	XKBLAYOUT=us  # U.S. English
	;;
    *_VN*)
	XKBLAYOUT=vn  # Vietnam
	;;
    *_ZA*)
	XKBLAYOUT=za  # South Africa
	;;
    # Keyboards for specific languages and international keyboards:
    # TODO: Is the following list correct?
    *_AR*|*_BO*|*_CL*|*_CO*|*_CR*|*_DO*|*_EC*|*_GT*|*_HN*|*_MX*|*_NI*|*_PA*|*_PE*|es_PR*|*_PY*|*_SV*|es_US*|*_UY*|*_VE*)
	XKBLAYOUT=latam # Latin American
	;;
    ar_*)
	XKBLAYOUT=us,ara # Arabic
	;;
    bn_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,ben # Bengali
	;;
    bs_*)
	XKBLAYOUT=ba  # Bosnia and Herzegovina
	;;
    de_LI*)
	XKBLAYOUT=ch  # Liechtenstein
	;;
    de_*)
	XKBLAYOUT=de  # Germany
	;;
    el_*)
	XKBLAYOUT=us,gr  # Greece
	;;
    eo|eo.*|eo_*|eo\@*)
	XKBLAYOUT=epo  # Esperanto
	layout_priority=critical
	;;
    fr_*)
	XKBLAYOUT=fr  # France
	XKBVARIANT=latin9
	layout_priority=critical
	;;
    gu_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,guj # Gujarati
	;;
    hi_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,deva # Devanagari
	;;
    hr_*)
	XKBLAYOUT=hr  # Croatia
	;;
    hy_*)
	XKBLAYOUT=us,am  # Armenia
	;;
    ka_*)
	XKBLAYOUT=us,ge  # Georgia
	layout_priority=critical
	;;
    kn_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,kan # Kannada
	;;
    ku_*)
	XKBLAYOUT=tr  # Turkish
	XKBVARIANT=ku # Kurdish
	layout_priority=critical
	;;
    lo_*)
	XKBLAYOUT=us,la  # Laos
	;;
    ml_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,mal # Malayalam
	;;
    os_*)
	XKBLAYOUT=ru  # Russia
	XKBVARIANT=os  # Ossetian
	;;
    pa_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,guru # Gurmukhi
	;;
    si_*)
	XKBLAYOUT=us,si  # Sri Lanka
	XKBVARIANT=,sin_phonetic # Sinhala
	;;
    sr_*)
	XKBLAYOUT=cs,cs  # Serbia and Montenegro
	XKBVARIANT=latin,basic
	layout_priority=critical
	;;
    sv_*)
	XKBLAYOUT=se  # Sweden
	;;
    ta_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,tam # Tamil
	;;
    te_*)
	XKBLAYOUT=us,in  # India
	XKBVARIANT=,tel # Telugu
	;;
    ug_*)
	XKBLAYOUT=us,cn  # China
	XKBVARIANT=,uig # Uyghur
	;;
    zh_*)
	XKBLAYOUT=cn  # Chinese
	;;
    # Fallback
    *)
	XKBLAYOUT=us
	;;
esac

### READ THE DEFAULTS ##################################################

# Get defaults from debconf, to allow preseeding in the udeb
if db_get keyboard-configuration/modelcode && [ "$RET" ]; then
    XKBMODEL="$RET"
fi
if db_get keyboard-configuration/layoutcode && [ "$RET" ]; then
    XKBLAYOUT="$RET"
fi
if db_get keyboard-configuration/variantcode && [ "$RET" ]; then
    XKBVARIANT="$RET"
fi
if db_get keyboard-configuration/optionscode && [ "$RET" ]; then
    XKBOPTIONS="$RET"
fi

# Use the value of console-data debian-installer/keymap to get better default
# layout.  This guesswork is copied from xserver-xorg.config.
# Lower the priority of the Debconf question to medium.
if db_get debian-installer/keymap && [ "$RET" ]; then
    di_keymap="${RET##mac-usb-}"
    di_keymap="${di_keymap%%-latin1}"
    
    old_xkbvariant="$XKBVARIANT"
    XKBVARIANT=''
    old_layout_priority=$layout_priority
    layout_priority=medium
    case "$di_keymap" in
	be2) XKBLAYOUT="be";;
	bg) XKBLAYOUT="us,bg";;
	br) XKBLAYOUT="us"; XKBVARIANT="intl";;
	br-abnt2) XKBLAYOUT="br"; XKBVARIANT="abnt2";;
	by) XKBLAYOUT="us,by";;
	cf) XKBLAYOUT="ca"; XKBVARIANT="fr";;
	croat) XKBLAYOUT="hr";;
	cz-lat2) XKBLAYOUT="cz";;
	de-latin1-nodeadkeys) XKBLAYOUT="de"; XKBVARIANT="nodeadkeys";;
	de) XKBLAYOUT="de";;
	dvorak) XKBLAYOUT="us"; XKBVARIANT="dvorak";;
	dk) XKBLAYOUT="dk";;
	es) XKBLAYOUT="es";;
	et) XKBLAYOUT="ee";;
	'fi') XKBLAYOUT="fi";;
	fr-latin9) XKBLAYOUT="fr"; XKBVARIANT="latin9";;
	fr_CH) XKBLAYOUT="ch"; XKBVARIANT="fr";;
	fr) XKBLAYOUT="fr";;
	hebrew) XKBLAYOUT="us,il";;
	hu) XKBLAYOUT="hu";;
	gb) XKBLAYOUT="gb";;
	is) XKBLAYOUT="is";;
	it) XKBLAYOUT="it";;
	jp106) XKBLAYOUT="jp"; XKBVARIANT="106";;
	la) XKBLAYOUT="latam";;
	lt) XKBLAYOUT="lt";; 
	lv-latin4) XKBLAYOUT="lv";;
	mac-us-std) XKBLAYOUT="us";;
	mac-de2-ext) XKBLAYOUT="de"; XKBVARIANT="nodeadkeys";;
	mac-fr2-ext) XKBLAYOUT="fr";;
	mac-fr3) XKBLAYOUT="fr";;
	mac-es) XKBLAYOUT="es";;
	ky) XKBLAYOUT="us,kg";;
	mk) XKBLAYOUT="us,mk";;
	nl) XKBLAYOUT="nl";;
	no) XKBLAYOUT="no";;
	pl) XKBLAYOUT="pl";;
	pt) XKBLAYOUT="pt";;
	ro) XKBLAYOUT="ro";;
	ru) XKBLAYOUT="us,ru";;
	se) XKBLAYOUT="se";;
	sg) XKBLAYOUT="ch"; XKBVARIANT="de";;
	sk-qwerty) XKBLAYOUT="sk"; XKBVARIANT="qwerty";;
	slovene) XKBLAYOUT="si";;
	sr-cy) XKBLAYOUT="cs,cs"; XKBVARIANT="latin,basic" ;;
	trf|trfu) XKBLAYOUT="tr"; XKBVARIANT="f";;
	trq|trqu) XKBLAYOUT="tr";;
	ua) XKBLAYOUT="us,ua";;
	uk) XKBLAYOUT="gb";;
	us) XKBLAYOUT="us";;
	*) 
	    XKBVARIANT="$old_xkbvariant"
	    layout_priority=$old_layout_priority
	    ;;
    esac
fi

# Get default layout from xorg.conf if available
# Lower the priority of the Debconf question to medium.
if \
    [ -f /etc/X11/xorg.conf -a ! -e $CONFIGFILE ] \
    && type awk 2>/dev/null >/dev/null
then
    awk_expr='
{
    sub("#.*","")
    line = $0;
    $0 = tolower($0);
    xkb = "";
}

/^[ \t]*section[ \t]+"inputdevice"/,/^[ \t]*endsection/ {
    if ($1 == "option") {
	if ($2 == "\"xkbmodel\"") {
	    xkb = "XKBMODEL";
	} else if ($2 == "\"xkblayout\"") {
	    xkb = "XKBLAYOUT";
	    print "layout_priority=medium";
	} else if ($2 == "\"xkbvariant\"") {
	    xkb = "XKBVARIANT";
	} else if ($2 == "\"xkboptions\"") {
	    xkb = "XKBOPTIONS"; 
	}
	$0 = line;
	$1 = "";
	$2 = "";
    }
}

xkb != "" && /^[ \t]*\"[^"]+\"[ \t]*$/ {
    sub("^[ \t]*\"", "");
    sub("\".*", "");
    gsub("[ \t]", "");
    if ($1 !~ /[()]/) {
	print xkb "=\"" $0 "\"";
    } else {
	if (xkb == "XKBLAYOUT" && $1 ~ /^[^()]+\([^()]+\)$/) {
	    l=$1;                      # us(intl),cz(qwerty)
	    gsub(/\([^()]*\)/,"",l);   # us,cz
	    v=$1;                      # us(intl),cz(qwerty)     us,bg
	    gsub(/\)/,"",v);           # us(intl,cz(qwerty       us,bg
	    gsub(/^[^(,]*,/,",",v);    # us(intl,cz(qwerty       ,bg
	    gsub(/^[^(,]*$/,"",v);     # us(intl,cz(qwerty       ,bg
	    gsub(/^[^(,]*\(/,"",v);    # intl,cz(qwerty          ,bg
	    gsub(/,[^(,]*,/,",,",v);   # intl,cz(qwerty          ,bg
	    gsub(/,[^(,]*$/,",",v);    # intl,cz(qwerty          ,
	    gsub(/,[^(,]*\(/,",",v);   # intl,qwerty             ,
	    print "XKBLAYOUT=" l;
	    print "XKBVARIANT=" v;
	}
    }
}
'
    eval $(awk "$awk_expr" < /etc/X11/xorg.conf)
fi

# Load the config file, if it exists.
if [ -e $OLDCONFIGFILE ]; then
    . $OLDCONFIGFILE || true
fi
if [ -e $CONFIGFILE ]; then
    . $CONFIGFILE || true
fi

# Compute default values for the Debconf questions

XKBMODEL=$(echo $XKBMODEL | sed 's/ *//g')
XKBLAYOUT=$(echo $XKBLAYOUT | sed 's/ *//g')
XKBVARIANT=$(echo $XKBVARIANT | sed 's/ *//g')

if [ "$XKBLAYOUT" ]; then
    case "$XKBLAYOUT" in
	lt,lt)
	    default_layout="${XKBLAYOUT%,*}"
	    default_variant="${XKBVARIANT%,*}"
	    unsupported_layout=no
	    ;;
	jp,jp|us,jp)
	    # fix on upgrade for #526862
	    default_layout="${XKBLAYOUT#*,}"
	    default_variant="${XKBVARIANT#*,}"
	    unsupported_layout=no
	    ;;
	# TODO: make s.t. to not forget to update this list
	cs,cs|us,am|us,af|us,ara|us,ben|us,bd|us,bg|us,bt|us,by|us,deva|us,et|us,ge|us,gh|us,gr|us,guj|us,guru|us,il|us,in|us,ir|us,iku|us,iq|us,ir|us,kan|us,kh|us,kz|us,la|us,lao|us,lk|us,lt|us,kg|us,ma|us,mal|us,mk|us,mm|us,mn|us,mv|us,np|us,ori|us,pk|us,ru|us,scc|us,sy|us,syr|us,tel|us,th|us,tj|us,tam|us,ua|us,uig|us,uz)
	    if [ "${XKBVARIANT%,*}" = '' ]; then
		default_layout="${XKBLAYOUT#*,}"
		default_variant="${XKBVARIANT#*,}"
		unsupported_layout=no
	    else
		unsupported_layout=yes
	    fi
	    ;;	    
	*,*)
	    unsupported_layout=yes
	    ;;
	*)
	    default_layout="$XKBLAYOUT"
	    default_variant="$XKBVARIANT"
	    ;;
    esac
fi

if \
    ! echo "$kbdnames" \
    | grep "variant[*]$default_layout[*]$default_variant[*]" >/dev/null
then
    unsupported_layout=yes
    default_variant=''
    if \
	! echo "$kbdnames" \
	| grep "layout[*]$default_layout[*]" >/dev/null
    then
	default_layout=us
    fi
fi

# since there are two completely different layouts 
if [ "$default_layout" = bg -a -z "$default_variant" ]; then
    default_variant=bds
    [ "$layout_priority" = critical ] || layout_priority=high
fi

default_toggle='Alt+Shift'
default_switch='No temporary switch'
default_altgr='The default for the keyboard layout'
default_compose='No compose key'
default_ctrl_alt_bksp=false
if [ "$XKBOPTIONS" ]; then
    default_toggle='No toggling'
    default_switch='No temporary switch'
    default_altgr='The default for the keyboard layout'
    default_compose='No compose key'
    for option in `echo $XKBOPTIONS | sed 's/,/ /g'`; do
	case "$option" in
	    compose:caps)
		default_compose='Caps Lock';;
	    compose:lwin)
		default_compose='Left Logo key';;
	    compose:menu)
		default_compose='Menu key';;
	    compose:ralt)
		default_compose='Right Alt (AltGr)';;
	    compose:rctrl)
		default_compose='Right Control';;
	    compose:rwin)
		default_compose='Right Logo key';;
	    grp:alt_caps_toggle)
		default_toggle='Alt+Caps Lock';;
	    grp:alt_shift_toggle)
		default_toggle='Alt+Shift';;
	    grp:caps_toggle)
		default_toggle='Caps Lock';;
	    grp:ctrl_alt_toggle)
		default_toggle='Control+Alt';;
	    grp:ctrl_shift_toggle)
		default_toggle='Control+Shift';;
	    grp:lalt_toggle)
		default_toggle='Left Alt';;
	    grp:lctrl_lshift_toggle)
		default_toggle='Left Control+Left Shift';;
	    grp:lctrl_toggle)
		default_toggle='Left Control';;
	    grp:lshift_toggle)
		default_toggle='Left Shift';;
	    grp:lswitch)
		default_switch='Left Alt';;
	    grp:lwin_switch)
		default_switch='Left Logo key';;
	    grp:lwin_toggle)
		default_toggle='Left Logo key';;
	    grp:menu_toggle)
		default_toggle='Menu key';;
	    grp:rctrl_toggle)
		default_toggle='Right Control';;
	    grp:rshift_toggle)
		default_toggle='Right Shift';;
	    grp:rwin_switch)
		default_switch='Right Logo key';;
	    grp:rwin_toggle)
		default_toggle='Right Logo key';;
	    grp:sclk_toggle)
		default_toggle='Scroll Lock key';;
	    grp:switch)
		default_switch='Right Alt (AltGr)';;
	    grp:toggle)
		default_toggle='Right Alt (AltGr)';;
	    grp:win_switch)
		default_switch='Both Logo keys';;
	    lv3:ralt_alt)
		default_altgr='No AltGr key';;
	    lv3:alt_switch)
		default_altgr='Both Alt keys';;
	    lv3:enter_switch)
		default_altgr='Keypad Enter key';;
	    lv3:lalt_switch)
		default_altgr='Left Alt';;
	    lv3:lwin_switch)
		default_altgr='Left Logo key';;
	    lv3:menu_switch)
		default_altgr='Menu key';;
	    lv3:ralt_switch)
		default_altgr='Right Alt (AltGr)';;
	    lv3:rwin_switch)
		default_altgr='Right Logo key';;
	    lv3:switch)
		default_altgr='Right Control';;
	    lv3:win_switch)
		default_altgr='Both Logo keys';;
	    terminate:ctrl_alt_bksp)
		default_ctrl_alt_bksp=true;;
	    grp_led:scroll)
		;;
	    *)
		unsupported_options=yes
		;;
	esac
    done
fi

# Store the default values into debconf db.
db_default keyboard-configuration/toggle "$default_toggle"
db_default keyboard-configuration/switch "$default_switch"
db_default keyboard-configuration/altgr "$default_altgr"
db_default keyboard-configuration/compose "$default_compose"
db_default keyboard-configuration/ctrl_alt_bksp "$default_ctrl_alt_bksp"
if [ ! "$unsupported_layout" = yes ]
then
    if [ -n "$default_variant" ]
    then
	default_keymap="$default_layout($default_variant)"
    else
	default_keymap="$default_layout"
    fi
fi
db_default keyboard-configuration/xkb-keymap "$default_keymap"
initial_xkbmodel="$XKBMODEL"

#######################################################################

# Version 1.37 of console-setup would destroy the values of $XKBMODEL,
# $XKBLAYOUT and $XKBVARIANT in the configfile if sharutils was not
# installed.  Version 1.47 destroyed $XKBMODEL.

if [ -z "$XKBMODEL" ]; then
    model_priority=critical
    XKBMODEL=pc105
    db_fset keyboard-configuration/model seen false
fi
if [ -z "$XKBLAYOUT" ]; then
    layout_priority=critical
    unsupported_layout=no
    XKBLAYOUT=us
    default_layout=us
    db_fset keyboard-configuration/layout seen false
    db_fset keyboard-configuration/variant seen false
fi

#######################################################################

if ! keyboard_present; then
    # No questions, just store the defaults for postinst
    db_set keyboard-configuration/modelcode "$XKBMODEL"
    db_set keyboard-configuration/layoutcode "$XKBLAYOUT"
    db_set keyboard-configuration/variantcode "$XKBVARIANT"
    if [ -z "$XKBOPTIONS" -a ! -f $CONFIGFILE ]; then
	case "$XKBLAYOUT" in
	    *,*) XKBOPTIONS="grp:alt_shift_toggle,grp_led:scroll";;
	    us) XKBOPTIONS="";;
	    *) XKBOPTIONS="lv3:ralt_switch";;
	esac
    fi
    db_set keyboard-configuration/optionscode "$XKBOPTIONS"
    exit 0
fi

STATE=1
old_state=0
while :; do
    starting_state=$STATE
    case "$STATE" in
	1)
	    if [ "$is_debian_installer" ]; then
		# do not ask model question in Debian installer
		db_set keyboard-configuration/modelcode "$XKBMODEL"
		db_fset keyboard-configuration/model seen true
		# skip the question without making Debconf loop
		STATE=$(( $STATE + $STATE - $old_state ))
	    else
		if [ "$XKBMODEL" = unknown ]; then
		    model_priority=critical
		    db_fset keyboard-configuration/model seen false
		fi
		if \
		    ask_debconf keyboard-configuration/model $model_priority \
		        model "$XKBMODEL"
		then
		    XKBMODEL="$RET"
		    db_set keyboard-configuration/modelcode "$RET"
		    STATE=$(($STATE + 1))
		else
		    STATE=$(($STATE - 1))
		fi
	    fi
	    ;;
	2)
	    if \
                [ "$unsupported_layout" = yes -a "$is_not_debian_installer" ]
            then
		case "$XKBVARIANT" in
		    ,|,,|,,,|'')
			unsupported_variant=''
			;;
		    *)
			unsupported_variant="/$XKBVARIANT"
			;;
		esac
		if [ -f $CONFIGFILE ]; then
		    db_subst keyboard-configuration/unsupported_config_layout \
			XKBLAYOUT "$XKBLAYOUT"
		    db_subst keyboard-configuration/unsupported_config_layout \
			XKBVARIANT "$XKBVARIANT"
		    db_input medium keyboard-configuration/unsupported_config_layout \
			|| true
		    if db_go; then 
			STATE=$(($STATE + 1))
		    else
			STATE=$(($STATE - 1))
		    fi
		    db_get keyboard-configuration/unsupported_config_layout
		else
		    db_subst keyboard-configuration/unsupported_layout \
			XKBLAYOUT "$XKBLAYOUT"
		    db_subst keyboard-configuration/unsupported_layout \
			XKBVARIANT "$XKBVARIANT"
		    db_subst keyboard-configuration/unsupported_layout \
			XKBLAYOUTVARIANT "$XKBLAYOUT$unsupported_variant"
		    db_input medium keyboard-configuration/unsupported_layout || true
		    if db_go; then 
			STATE=$(($STATE + 1))
		    else
			STATE=$(($STATE - 1))
		    fi
		    db_get keyboard-configuration/unsupported_layout
		fi
		if [ "$RET" != true ]; then
		    unsupported_layout=no
		fi
	    else
		db_reset keyboard-configuration/unsupported_config_layout || true
		db_fset keyboard-configuration/unsupported_config_layout seen false
		db_reset keyboard-configuration/unsupported_layout || true
		db_fset keyboard-configuration/unsupported_layout seen false
		# skip the question without making Debconf loop
		STATE=$(( $STATE + $STATE - $old_state ))
	    fi
	    ;;
	3)
	    if [ "$is_debian_installer" ]; then
		# ask simplified layout question in Debian installer
		db_input critical keyboard-configuration/xkb-keymap || true
		if db_go; then 
		    STATE=$(($STATE + 1))
		else
		    STATE=$(($STATE - 1))
		fi
		db_get keyboard-configuration/xkb-keymap
		keymap="$RET"
		layout="${keymap%(*}"
		variant="${keymap#$layout}"
		variant="${variant%)}"
		variant="${variant#(}"
		default_layout="$layout"
		default_variant="$variant"
		db_fset keyboard-configuration/layout seen true
		db_fset keyboard-configuration/variant seen true
	    elif \
		[ "$unsupported_layout" = yes -o "$default_variant" != other ]
	    then
		layout="$default_layout"
		db_set keyboard-configuration/layoutcode "$XKBLAYOUT"
		# skip the question without making Debconf loop
		STATE=$(( $STATE + $STATE - $old_state ))
	    elif \
		ask_debconf keyboard-configuration/layout "$layout_priority" \
		    layout "$default_layout"
	    then
		default_layout="$RET"
		layout="$RET"
		STATE=$(($STATE + 1)) 
	    else
		# always to the next question
		STATE=$(($STATE + 1))
	    fi
	    ;;
	4)
	    db_metaget keyboard-configuration/other description
	    other="$RET"
	    if [ "$unsupported_layout" = yes ]; then
                variant=none
                case "$XKBLAYOUT" in
                    *,*)
                        latin=no
                        ;;
                    *)
                        latin=yes
                        ;;
                esac
		db_set keyboard-configuration/variantcode "$XKBVARIANT"
		# skip the question without making Debconf loop
		STATE=$(( $STATE + $STATE - $old_state ))
            elif [ "$is_not_debian_installer" ]; then
                if \
		    ! ask_debconf keyboard-configuration/variant \
                                  "$layout_priority" \
                                  "variant*${layout}" "$default_variant" \
                                  "variant*${layout}*other*$other"
                then
                    variant=none
		    # skip the previous question
		    starting_state=$(($STATE - 1))
		    STATE=$(($STATE - 2))
                elif [ "$RET" = other ]; then
                    variant=none
                    default_variant="$RET"
		    STATE=$(($STATE - 1))
                else
                    variant="$RET"
                    default_variant="$RET"
                fi
            fi
            if [ "$variant" != none ]; then
		case "$layout" in
		    cs)
			case "$variant" in
			    latin*)
				latin=yes
				XKBLAYOUT=$layout
				;;
			    *)
				latin=no
				XKBLAYOUT=cs,cs
				;;
			esac
			;;
		    jp)
			case "$variant" in
			    106|common|OADG109A|'')
				latin=yes
				XKBLAYOUT=$layout
				;;
			    *)
				latin=no
				XKBLAYOUT=jp,jp
				;;
			esac
			;;
		    lt)
			latin=no
			XKBLAYOUT=lt,lt
			;;
		    # TODO: make s.t. to not forget to update this list.  Don't
		    # forget to update also the nonlatin list in kbdcompiler
		    af|am|ara|ben|bd|bg|bt|by|deva|et|ge|gh|gr|guj|guru|il|in|iq|ir|iku|kan|kh|kz|la|lao|lk|kg|ma|mk|mm|mn|mv|mal|np|ori|pk|ru|scc|sy|syr|tel|th|tj|tam|ua|uig|uz)
			latin=no
			XKBLAYOUT=us,$layout
			;;
		    *)
			latin=yes
			XKBLAYOUT=$layout
			;;
		esac
		db_set keyboard-configuration/layoutcode "$XKBLAYOUT"
		if [ "$latin" = yes ]; then
		    db_set keyboard-configuration/variantcode "$variant"
		elif [ "$XKBLAYOUT" = cs,cs ]; then
		    case "$variant" in
			yz)
			    db_set keyboard-configuration/variantcode \
				"latinyz,$variant"
			    ;;
			alternatequotes)
			    db_set keyboard-configuration/variantcode \
				"latinalternatequotes,$variant"
			    ;;
			*)
			    db_set keyboard-configuration/variantcode \
				"latin,$variant"
			    ;;
		    esac
		elif [ "$XKBLAYOUT" = lt,lt ]; then
		    case "$variant" in
			us)
			    db_set keyboard-configuration/variantcode "us,"
			    ;;
			*)
			    db_set keyboard-configuration/variantcode "$variant,us"
			    ;;
		    esac
		else
		    db_set keyboard-configuration/variantcode ",$variant"
		fi
		STATE=$(($STATE + 1))
	    fi
	    ;;
	5)
	    if \
		[ "$unsupported_options" = yes -a "$is_not_debian_installer" ]
	    then
		if [ -f $CONFIGFILE ]; then
		    db_subst keyboard-configuration/unsupported_config_options \
			XKBOPTIONS "$XKBOPTIONS"
		    db_input medium keyboard-configuration/unsupported_config_options \
			|| true
		    if db_go; then 
			STATE=$(($STATE + 1))
		    else
			STATE=$(($STATE - 1))
		    fi
		    db_get keyboard-configuration/unsupported_config_options
		else
		    db_subst keyboard-configuration/unsupported_options \
			XKBOPTIONS "$XKBOPTIONS"
		    db_input medium keyboard-configuration/unsupported_options || true
		    if db_go; then 
			STATE=$(($STATE + 1))
		    else
			STATE=$(($STATE - 1))
		    fi
		    db_get keyboard-configuration/unsupported_options
		fi
		if [ "$RET" != true ]; then
		    unsupported_options=no
		fi
	    else
		db_reset keyboard-configuration/unsupported_config_options || true
		db_fset keyboard-configuration/unsupported_config_options seen false
		db_reset keyboard-configuration/unsupported_options || true
		db_fset keyboard-configuration/unsupported_options seen false
		# skip the question without making Debconf loop
		STATE=$(( $STATE + $STATE - $old_state ))
	    fi
	    ;;
	6)
	    if [ "$unsupported_options" = yes ]; then
		db_set keyboard-configuration/optionscode "$XKBOPTIONS"
		# skip the questions without making Debconf loop
		STATE=$(( $STATE + $STATE - $old_state ))
	    else
		caps_allocated=no
		lalt_allocated=no
		lctrl_allocated=no
		lshift_allocated=no
		lwin_allocated=no
		menu_allocated=no
		ralt_allocated=no
		rctrl_allocated=no
		rshift_allocated=no
		rwin_allocated=no

		if [ "$latin" = yes ]; then
		    db_set keyboard-configuration/toggle 'No toggling'
		    db_set keyboard-configuration/switch 'No temporary switch'
		fi

		db_beginblock
		if [ "$latin" = no ]; then
		    db_input high keyboard-configuration/toggle || true
		    if [ "$is_not_debian_installer" ]; then
			db_input medium keyboard-configuration/switch || true
		    fi
		fi
		if [ "$is_not_debian_installer" ]; then
		    db_input medium keyboard-configuration/altgr || true
		    db_input medium keyboard-configuration/compose || true
		fi
		if [ -f /usr/bin/X ]; then
		    db_input medium keyboard-configuration/ctrl_alt_bksp || true
		fi
		db_endblock

		if db_go; then 
		    STATE=$(($STATE + 1))
		else
		    STATE=$(($STATE - 1))
		fi

		db_get keyboard-configuration/toggle
		case "$RET" in
		    Caps\ Lock)
		        caps_allocated=yes
		        toggle=caps_toggle;;
		    Right\ Alt*)
		        ralt_allocated=yes
		        toggle=toggle;;
		    Right\ Control)
		        rctrl_allocated=yes
		        toggle=rctrl_toggle;;
		    Right\ Shift)
		        rshift_allocated=yes
		        toggle=rshift_toggle;;
		    Right\ Logo?key)
		        rwin_allocated=yes
		        toggle=rwin_toggle;;
		    Menu?key)
			menu_allocated=yes
			toggle=menu_toggle;;
		    Alt+Shift)
			toggle=alt_shift_toggle;;
		    Control+Shift)
			toggle=ctrl_shift_toggle;;
		    Left\ Control+Left\ Shift)
			toggle=lctrl_lshift_toggle;;
		    Scroll\ Lock\ key)
			toggle=sclk_toggle;;
		    Alt+Caps\ Lock)
			toggle=alt_caps_toggle;;
		    Control+Alt)
			toggle=ctrl_alt_toggle;;
		    Left\ Alt)
		        lalt_allocated=yes
		        toggle=lalt_toggle;;
		    Left\ Control)
		        lctrl_allocated=yes
		        toggle=lctrl_toggle;;
		    Left\ Shift)
		        lshift_allocated=yes
		        toggle=lshift_toggle;;
		    Left\ Logo?key)
		        lwin_allocated=yes
		        toggle=lwin_toggle;;
		    No\ toggling)
		        toggle='';;
		    *)
			echo Unknown toggle key option
			exit 1
			;;
		esac
		if [ "$toggle" ]; then
		    toggle=grp:$toggle
		fi
		
		db_get keyboard-configuration/switch
		switch=''
		case "$RET" in
		    Right\ Alt*)
		        if [ "$ralt_allocated" != yes ]; then
			    switch=switch
			    ralt_allocated=yes
		        fi;;
		    Left\ Alt)
		        if [ "$lalt_allocated" != yes ]; then
			    switch=lswitch
			    lalt_allocated=yes
		        fi;;
		    Right\ Logo?key)
		        if [ "$rwin_allocated" != yes ]; then
			    switch=rwin_switch
			    rwin_allocated=yes
		        fi;;
		    Left\ Logo?key)
		        if [ "$lwin_allocated" != yes ]; then
			    switch=lwin_switch
			    lwin_allocated=yes
		        fi;;
		    Both\ Logo?keys)
		        if \
			    [ "$rwin_allocated" != yes ] \
			    && [ "$lwin_allocated" != yes ]
			then
			    switch=win_switch
			    rwin_allocated=yes
			    lwin_allocated=yes
		        fi;;
		    No\ temporary\ switch)
		        switch='';;
		    *)
			echo Unknown switch key option
			exit 1
			;;
		esac
		if [ "$switch" ]; then
		    switch=grp:$switch
		fi
		
		db_get keyboard-configuration/altgr
		altgr=''
		case "$RET" in
		    The?default?for?the?keyboard?layout)
			altgr='';;
		    No?AltGr?key)
			if [ "$ralt_allocated" != yes ]; then
			    # no need for ralt_allocated=yes
			    altgr=ralt_alt
			fi;;
		    Right?Alt*)
			if [ "$ralt_allocated" != yes ]; then
			    altgr=ralt_switch
			    ralt_allocated=yes
			fi;;
		    Right?Control)
			if [ "$rctrl_allocated" != yes ]; then
			    altgr=switch
			    rctrl_allocated=yes
			fi;;
		    Menu?key)
			if [ "$menu_allocated" != yes ]; then
			    altgr=menu_switch
			    menu_allocated=yes
			fi;;
		    Keypad?Enter?key)
			altgr=enter_switch;;
		    Right?Logo?key)
			if [ "$rwin_allocated" != yes ]; then
			    altgr=rwin_switch
			    rwin_allocated=yes
			fi;;
		    Left?Logo?key)
			if [ "$lwin_allocated" != yes ]; then
			    altgr=lwin_switch
			    lwin_allocated=yes
			fi;;
		    Both?Logo?keys)
			if \
			    [ "$rwin_allocated" != yes ] \
			    && [ "$lwin_allocated" != yes ]
			then
			    altgr=win_switch
			    rwin_allocated=yes
			    lwin_allocated=yes
			fi;;
		    Both?Alt?keys)
			if \
			    [ "$lalt_allocated" != yes ] \
			    && [ "$ralt_allocated" != yes ]
			then
			    altgr=alt_switch
			    ralt_allocated=yes
			    lalt_allocated=yes
			fi;;
		    Left?Alt)
			if [ "$lalt_allocated" != yes ]; then
			    altgr=lalt_switch
			    lalt_allocated=yes
			fi;;
		    *)
			echo Unknown altgr key option
			exit 1
			;;
		esac
		if [ "$altgr" ]; then
		    altgr=lv3:$altgr
		fi

		db_get keyboard-configuration/compose
		compose=''
		case "$RET" in
		    No?compose?key)
			compose='';;
		    Right?Alt*)
			if [ "$ralt_allocated" != yes ]; then
			    compose=ralt
			    ralt_allocated=yes
			fi;;
		    Right?Logo?key)
			if [ "$rwin_allocated" != yes ]; then
			    compose=rwin
			    rwin_allocated=yes
			fi;;
		    Left?Logo?key)
			if [ "$lwin_allocated" != yes ]; then
			    compose=lwin 
			    lwin_allocated=yes
			fi;;
		    Right?Control)
			if [ "$rctrl_allocated" != yes ]; then
			    compose=rctrl 
			    rctrl_allocated=yes
			fi;;
		    Menu?key)
			if [ "$menu_allocated" != yes ]; then
			    compose=menu
			    menu_allocated=yes
			fi;;
		    Caps?Lock)
			if [ "$caps_allocated" != yes ]; then
			    compose=caps
			    caps_allocated=yes
			fi;;
		    *)
			echo Unknown compose key option
			exit 1
			;;
		esac
		if [ "$compose" ]; then
		    compose=compose:$compose
		fi
		
		db_get keyboard-configuration/ctrl_alt_bksp
		if [ "$RET" = true ]; then
		    terminate=terminate:ctrl_alt_bksp
		else
		    terminate=''
		fi
		
		# A fix for #566009
		if [ "$ralt_allocated" = yes -a "$altgr" = lv3:ralt_alt ]; then
		    altgr=''
		fi

		case "$XKBLAYOUT" in
		    *,*)
		        leds=grp_led:scroll;;
		    *)
			leds='';;
		esac
		
		options=$(
		    echo $toggle $switch $altgr $compose $terminate $leds \
			| sed -e 's/^ *//' -e 's/ *$//' -e 's/  */,/g'
		)
		db_set keyboard-configuration/optionscode "$options"
	    fi
	    ;;
	*)
	    break
	    ;;
    esac
    old_state=$starting_state
done

if [ $STATE -eq 0 ]; then
    exit 10
else
    db_set keyboard-configuration/store_defaults_in_debconf_db false
fi

exit 0
