#!/bin/sh

LAYOUT_DIR="/usr/X11R6/lib/X11/xkb/rules/"
if [ -e $LAYOUT_DIR/xorg.lst ]; then
	LAYOUT_FILE="xorg.lst"
else
	LAYOUT_FILE="xfree86.lst"
fi
DIALOG_FILE="/root/layout_dialog.sh"
XF86_CFG="/etc/X11/XF86Config"
XF86_TMP_CFG="/tmp/XF86Config"

if [ -e ${LAYOUT_DIR}${LAYOUT_FILE} ]; then
    cp ${LAYOUT_DIR}${LAYOUT_FILE} .
else
    echo "Problems with XFree86 sources"
    exit -1
fi

rm -f $DIALOG_FILE

echo "dialog --title \"FreeSBIE XFree86 Layout\" \
    --menu \"Choose your preferred keyboard layout\" 22 50 15 \\" >> ${DIALOG_FILE}

awk '{
if ($1 == "!") {
    if ($2 == "layout") {
        getline;
        while ($0 != "!" && $0 != "") {
            print $1 "\t\"" $2 "\" \\";
            getline;
        }
    }
}
}' $LAYOUT_FILE >> ${DIALOG_FILE}
rm $LAYOUT_FILE
echo "2> /root/.choose" >> ${DIALOG_FILE}
sh ${DIALOG_FILE}
rm -f ${DIALOG_FILE}
LAYOUT=`cat /root/.choose`
echo "Detected $LAYOUT"
rm -f /root/.choose
cp ${XF86_CFG} ${XF86_TMP_CFG}
sed "s/\"us\"/\"${LAYOUT}\"/" < ${XF86_TMP_CFG} > ${XF86_CFG}
rm -f ${XF86_TMP_CFG}
