#!/bin/sh
set -e

SEGGUI="/opt/seg-gui/Seg5Gui"
SEGPWD="/opt/seg-gui"
SEGOPTS="-platform eglfs -plugin Tslib"

SEG_SDCONF_PATH="/mnt/sdcard/.seg5/"
SEG_POINTERCAL="${SEG_SDCONF_PATH}/touchscreen/pointercal"
[ -f ${SEG_POINTERCAL} ] && export TSLIB_CALIBFILE=${SEG_POINTERCAL}

export SEG_SETTINGS_PATH=${SEG_SDCONF_PATH}/gui
export TSLIB_TSDEVICE=/dev/input/touchscreen0
export QWS_MOUSE_PROTO=/dev/input/event1
export TSLIB_CONFFILE=/etc/ts.conf
export TSLIB_PLUGINDIR=/usr/lib/ts

export TSLIB_CONSOLEDEVICE=/dev/tty
export TSLIB_FBDEVICE=/dev/fb0

# This hack disables evdevtouch events while using tslib.
# Change to QT_QPA_EGLFS_DISABLE_INPUT in Qt 5.3
# export QT_QPA_EGLFS_DISABLE_INPUT=1
export QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS=/dev/tty45
export QT_QPA_EGLFS_TSLIB=1

# include init functions
source /etc/init.d/functions

case "$1" in
  start)
      cd $SEGPWD
      echo -n "Starting SEG5 Gui Application: "
      start-stop-daemon -S -b -x $SEGGUI -- $SEGOPTS
      echo "done."
      ;;
  stop)
      echo -n "Stopping SEG5 Gui Application: "
      start-stop-daemon -K -R1 --oknodo -x $SEGGUI
      echo "."
      ;;
  restart)
      echo -n "Restarting SEG5 Gui Application: "
      start-stop-daemon -K -R1 --oknodo -x $SEGGUI
      sleep 2
      cd $SEGPWD
      start-stop-daemon -S -b -x $SEGGUI -- $SEGOPTS
      echo "."
      ;;
  status)
      status $SEGGUI
      exit $?
      ;;
  *)
      echo "Usage: /etc/init.d/seg_gui {start|stop|restart|status}"
      exit 1
esac

exit 0
