#!/bin/sh

# By Alan M Bruce (qole), from discoveries made by qobi and others
# on talk.maemo.org
#
# GPL licensed; keep code free!

if [ "`whoami`" = "root" ] ; then
  echo "please don't run me as root!"
  exit 9
fi

EXTKBD=`hildon-im-xkbtool --list | grep -v 'Virtual' | grep -v 'touchscreen' | grep -v 'omap'`
if [ "x$EXTKBD" = x ] ; then
  zenity --hildon --warning --text "No external keyboard found!"
  # echo "No keyboard found."
  exit 9
fi
EXTKBDID=`echo $EXTKBD | awk '{gsub(/[,]*/, "", $2); print $2 }'`

INTKBD=`hildon-im-xkbtool --list | grep -i "omap_twl4030keypad"`
INTKBDID=`echo $INTKBD | awk '{gsub(/[,]*/, "", $2); print $2 }'`
# echo "Int: ($INTKBDID) Ext: ($EXTKBDID)"

KBDRULES=base
KBDMODEL=pc105
KBDLAYOUT=us

#Pull in the config, if possible...

if [ -f /home/user/.btkeyboard ] ; then
  . /home/user/.btkeyboard
else

# No config found, make one.

  echo "# Config file for remapping the external keyboard" > /home/user/.btkeyboard
  echo " " >> /home/user/.btkeyboard
  echo "KBDRULES=$KBDRULES" >> /home/user/.btkeyboard
  echo "KBDMODEL=$KBDMODEL" >> /home/user/.btkeyboard
  echo "KBDLAYOUT=$KBDLAYOUT" >> /home/user/.btkeyboard

fi

EDMOUNT="no"

# Check to see if Easy Debian is running

if [ -f /home/user/.chroot ] 
  . /home/user/.chroot
  
  #Set keyboard map for :1 if chroot mounted.

  if [ -f "$CHROOT/var/lock/qmount-complete" ] ; then
    EDMOUNT="yes"
  fi
fi

if [ $EDMOUNT = yes ] ; then

  # Set layout for Easy Debian
  setxkbmap -device $EXTKBDID -I -I/usr/share/X11/xkb-chinook -rules $KBDRULES -model $KBDMODEL -layout $KBDLAYOUT | xkbcomp - :1 2>/dev/null

fi

# Set ext kbd layout for Maemo

setxkbmap -device $EXTKBDID -I -I/usr/share/X11/xkb-chinook -rules $KBDRULES -model $KBDMODEL -layout $KBDLAYOUT

if [ $EDMOUNT = yes ] ; then

  # Set int kbd layout for Maemo
  setxkbmap -device $INTKBDID -model nokiarx51

fi