#! /bin/sh
# chkconfig: 2345 80 27
### BEGIN INIT INFO
# Provides:          matrix-gui-v2
# Required-Start:    lighttpd
# Required-Stop:     lighttpd
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start matrix-gui-v2 at boot time
# Description:       Enable service provided by matrix-gui-v2.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  80
# X-Timesys-Stop-Number:  20
### END INIT INFO

DAEMON="/usr/bin/matrix_browser"
OPTIONS="-qws http://localhost:8080/"
PIDFILE="/var/run/matrix-gui-2.0.pid"

case "$1" in
  start)
    echo -n "Starting $DAEMON: "

    if [ ! -e /etc/ts.dev ]; then
      echo -n "Unable to find configured touchscreen device... "
      export QWS_MOUSE_PROTO=Auto
    else
      pointerdev=$(cat /etc/ts.dev)
      export TSLIB_TSDEVICE=$pointerdev
      export QWS_MOUSE_PROTO=Tslib:$pointerdev
    fi

    # Check if json.txt file needs to be generated
    if [ ! -f /usr/share/matrix-gui-2.0/json.txt ]; then
      oldwd=$(pwd)
      cd /usr/share/matrix-gui-2.0
	    rm -rf cache/* 
      php generate.php
      rm -rf tmp/* 
      rm -rf lock/*
      cd $oldwd
    fi

    if [ -f $PIDFILE ]; then
      PIDDIR=/proc/$(cat $PIDFILE)
      if [ -d ${PIDDIR} -a -n "$(readlink -f ${PIDDIR}/exe 2>/dev/null)" ]; then
        echo "$DAEMON already started; not starting."
        exit
      else
        echo "Removing stale PID file $PIDFILE."
        rm -f $PIDFILE
      fi
    fi

    $DAEMON $OPTIONS &
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "[FAIL]"
      exit $rc
    fi
	  pidof ${DAEMON} > $PIDFILE
    echo "[ OK ]"

  ;;
  stop)
    echo -n "Stoping $DAEMON: "
    if [  -r $PIDFILE  -a  ! -z ${PIDFILE}  ]; then
      PID=`cat ${PIDFILE}`
    fi
    if [  ${PID:=0} -gt 1 -a  ! "X$PID" = "X "  ]; then
      kill ${PID}
      echo "[ OK ]"
      rm -f $PIDFILE
    else
      echo "Unable to read PID file"
      exit 1
    fi
  ;;
  restart)
    $0 stop && $0 start
  ;;
  *)
    echo "Usage: $0 [start|stop|restart]"
  ;;
esac
