# This script is called from /etc/init.d/boot.local. It is intended to run
# only on first boot so it deletes itself after running.

# Fix our xorg.conf.testdrive according to the local keyboard settings
setup_keyboard() {
  # Because we're running before the keyboard selection, we need to hack into the
  # kdb script and do the replacement there. Once we did it, let's restore the
  # original script
  cp /etc/init.d/kbd{,.bkp}
  sed -i "s/rc_exit//" /etc/init.d/kbd
  cat >> /etc/init.d/kbd <<-'EOF'
    if [ -f /etc/X11/xorg.conf -a -x /usr/sbin/sysp ]; then
      echo -n "  -> Setting keyboard layout..."
      /usr/sbin/sysp -s keyboard &> /dev/null
      MODEL=$(/usr/sbin/sysp -q keyboard | grep XkbModel | sed 's/.*: //')
      LAYOUT=$(/usr/sbin/sysp -q keyboard | grep XkbLayout | sed 's/.*: //')
      VARIANT=$(/usr/sbin/sysp -q keyboard | grep XkbVariant | sed 's/.*: //')
      sed -i "s/{XKBLAYOUT}/$LAYOUT/;s/{XKBMODEL}/$MODEL/;s/{XKBVARIANT}/$VARIANT/" /etc/X11/xorg.conf
      echo "done"
    fi
    mv /etc/init.d/kbd{.bkp,}
    rc_exit
EOF
}

# Use the evtouch driver when in testdrive so that the mouse cursor works properly.
setup_evtouch() {
  # use xorg.conf.testdrive
  if [ -f /etc/X11/xorg.conf.testdrive ]; then
    echo -n "  -> Copying '/etc/X11/xorg.conf.testdrive' to '/etc/X11/xorg.conf'... "
    if [ -f /etc/X11/xorg.conf ]; then
      cp /etc/X11/xorg.conf /etc/X11/xorg.conf.tdsave
    fi
    cp /etc/X11/xorg.conf.testdrive /etc/X11/xorg.conf
    echo "done"
  else
    echo "  -> WARNING: '/etc/X11/xorg.conf.testdrive' not found! X startup may fail."
  fi
}

# Always use DHCP when in Testdrive.
use_dhcp() {
  sed -i '/^STARTMODE/c STARTMODE=auto' etc/sysconfig/network/ifcfg-eth0
  sed -i '/^BOOTPROTO/c BOOTPROTO=dhcp' etc/sysconfig/network/ifcfg-eth0
  sed -i '/^IPADDR/c IPADDR=' etc/sysconfig/network/ifcfg-eth0
  sed -i '/^NETMASK/c NETMASK=' etc/sysconfig/network/ifcfg-eth0
}

# ===========================================
# Check if we are in testdrive 
# -------------------------------------------

echo -n "Checking if we are in SUSE Studio TestDrive... "
if [ -e /dev/input/qemu_tablet ]; then
    echo "yes"
    setup_keyboard
    setup_evtouch
    use_dhcp
    sed -i 's|HWCLOCK="--localtime"|HWCLOCK="-u"|g' etc/sysconfig/clock;
else
    echo "no"
    rm /etc/X11/xorg.conf.testdrive
fi 

# delete itself, as we only need this to run on first boot
rm -f /etc/init.d/suse_studio_firstboot

