#!/bin/bash

PKG_DIR=$1
PKG_NAME=$2

INSTALL_DIR="/opt/readysetstem/ide"

#
# Enable boot to desktop...  Taken from http://github.com/asb/raspi-config
#

disable_raspi_config_at_boot() {
  if [ -e /etc/profile.d/raspi-config.sh ]; then
    rm -f /etc/profile.d/raspi-config.sh
    sed -i /etc/inittab \
      -e "s/^#\(.*\)#\s*RPICFG_TO_ENABLE\s*/\1/" \
      -e "/#\s*RPICFG_TO_DISABLE/d"
    telinit q
  fi
}

disable_boot_to_scratch() {
  if [ -e /etc/profile.d/boottoscratch.sh ]; then
    rm -f /etc/profile.d/boottoscratch.sh
    sed -i /etc/inittab \
      -e "s/^#\(.*\)#\s*BTS_TO_ENABLE\s*/\1/" \
      -e "/#\s*BTS_TO_DISABLE/d"
    telinit q
  fi
}

enable_boot_to_desktop() {
    update-rc.d lightdm enable 2
    sed /etc/lightdm/lightdm.conf -i -e "s/^#autologin-user=.*/autologin-user=pi/"
    disable_boot_to_scratch
    disable_raspi_config_at_boot
}

set_keyboard() {
    KBFILE="/etc/default/keyboard"
    KBSTRING='XKBLAYOUT="'"$1"'"'
    if ! tail -1 "$KBFILE" | grep -q '^'"$KBSTRING"'$'; then
        sudo sh -c 'echo '\'"$KBSTRING"\'' >> '"$KBFILE"
    fi
}

echo "Running postinstall script..."
echo "  Enabling boot to desktop"

enable_boot_to_desktop
set_keyboard us

# Add server startup to boot
update-rc.d rstem_ided defaults

# Autostart IDE client web browser
echo "  Enabling autostart of IDE client..."
LAUNCH_LINK="$INSTALL_DIR/launch"
LAUNCH_FILE="start_client.sh"
ln -sf "$LAUNCH_FILE" "$LAUNCH_LINK"
IDE_LINE="@$LAUNCH_LINK"
AUTOSTART_CFG="/home/pi/.config/lxsession/LXDE-pi/autostart"
if ! grep -q "$IDE_LINE" "$AUTOSTART_CFG"; then
    echo "$IDE_LINE" >> "$AUTOSTART_CFG"
    echo "    ... now enabled."
else
    echo "    ... was already enabled."
fi
chmod a+x  "$INSTALL_DIR/$LAUNCH_FILE"


# Create desktop icon
cp "$INSTALL_DIR/rss.desktop" /home/pi/Desktop

