#! /bin/sh

matrixgui="/usr/bin/qtopia/demos/browser/browser"
GUI_OPTS="-qws -nogui http://localhost:8080/index.html"
PIDFILE="/var/run/matrix-gui-2.0.pid"

test -x "$matrixgui" || exit 0

export TSLIB_TSDEVICE=/dev/input/touchscreen0
export QWS_MOUSE_PROTO=Tslib:/dev/input/touchscreen0

case "$1" in
  start)
    chvt 4

    # Temporarily create the /dev/input/touchscreen0 symlink if it is
    # not already present.  On devices like am335x the driver does not
    # report the right string in /sys/devices/platform/tsc/input/input0/modalias
    # to match the regular expression in /etc/udev/rules.d/local.rules
    # to have this symlink created automatically.
    if [ -e /dev/input/event0 ]
    then
        # assume we are going to use event0
        ln -s /dev/input/event0 /dev/input/touchscreen0

        if [ ! -f /etc/pointercal ] ; then
            echo -n "Calibrating touchscreen (first time only)"
            ts_calibrate
            echo "."
        fi
    fi

	if [ -e $PIDFILE ]; then
      PIDDIR=/proc/$(cat $PIDFILE)
      if [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${matrixgui}" ]; then
        echo "$DESC already started; not starting."
      else
        echo "Removing stale PID file $PIDFILE."
        rm -f $PIDFILE
      fi
    fi

    echo -n "Starting Matrix GUI application"
    cd __MATRIX_BASE_DIR__
    start-stop-daemon --start --quiet --background --exec node -- server.js
    # Need to investigate how to make the second start-stop command wait
    # until the start of node is done.
    sleep 5
    start-stop-daemon --start --quiet --background --exec $matrixgui -- $GUI_OPTS
	pidof ${matrixgui} > $PIDFILE
    echo "."
    ;;

  stop)
    echo -n "Stopping Matrix GUI application"
    start-stop-daemon --stop --quiet --pidfile /var/run/matrix-gui-2.0.pid
    echo "."
    ;;
  *)
    echo "Usage: /etc/init.d/matrix-gui-2.0 {start|stop}"
    exit 1
esac

exit 0
