#!/bin/sh

if [ $UID -ne 0 ]; then
  echo "You need to be root to run this program"
  exit 0
fi

configfile=/etc/sysconfig/keyboard
cachedir=/var/cache/xdm
cachefile=keyboard.last
halfile=/etc/hal/fdi/policy/20thirdparty/11-keymap.fdi

. ${configfile}

if [ -e $cachedir/$cachefile -a -e $halfile ]
then
    . $cachedir/$cachefile
    [ "$KEYTABLE" = "$cache_keytable" ] && exit 1;
fi

# layout is mandatory - but $keytable may be bogus
layout=us
variant=x
options=x

keytable=$(basename $KEYTABLE .map.gz)

layout=$(grep "^$keytable " /usr/share/sax/sysp/maps/Keyboard.map|cut -d ":" -f 3|sed 's/ //g')
variant=$(grep "^$keytable " /usr/share/sax/sysp/maps/Keyboard.map|cut -d ":" -f 4|sed 's/ //g')
options=$(grep "^$keytable " /usr/share/sax/sysp/maps/Keyboard.map|cut -d ":" -f 10-12|sed 's/ //g')
model=$(grep "^$keytable " /usr/share/sax/sysp/maps/Keyboard.map|cut -d ":" -f 2|sed 's/ //g')

# Once we are completely evdev
case $model in
    abnt2|jp106)
	;;
    *)
	model=evdev
	;;
esac

mkdir -p $(dirname $halfile)
cat > $halfile << EOF
<?xml version="1.0" encoding="ISO-8859-1"?> <!-- -*- SGML -*- -->
<deviceinfo version="0.2">
  <device>
    <match key="info.capabilities" contains="input.keymap">
      <append key="info.callouts.add" type="strlist">hal-setup-keymap</append>
    </match>

    <match key="info.capabilities" contains="input.keys">
      <merge key="input.xkb.rules" type="string">base</merge>
      <merge key="input.xkb.model" type="string">$model</merge>
      <merge key="input.xkb.layout" type="string">$layout</merge>
EOF

if [ "$variant" != "x" ]; then
    echo "      <merge key=\"input.xkb.variant\" type=\"string\">$variant</merge>" >> $halfile
else
    echo "      <merge key=\"input.xkb.variant\" type=\"string\" />" >> $halfile
fi
if [ "$options" != "x" ]; then
    echo "      <merge key=\"input.xkb.options\" type=\"string\">$options</merge>" >> $halfile
fi

cat >> $halfile << EOF
    </match>
  </device>
</deviceinfo>
EOF

mkdir -p $cachedir 2>/dev/null
echo cache_keytable=$KEYTABLE > $cachedir/$cachefile 2>/dev/null

exit 0
