#!/bin/bash
source /etc/profile
source /etc/default/gapp

CMD=$1
START_FLAG=/var/volatile/gappStart
shift

export LD_LIBRARY_PATH=/usr/lib/chrome:/opt/gira/lib
rm -f /opt/userdata/.chromium/SingletonLock
IMAGE_VERSION=$(</opt/extparam/booted_firmware_version)
if [ -z $IMAGE_VERSION ]
then
  . /etc/buildversion
fi

if [ -f "/opt/card/gira/demo/demo.sales" ]
then
	echo "start GiraApp in Demo Mode"
	startupLink="file:///opt/gira/share/devicestack/web/layout.html?g1=regular&demomode=true"
elif [  -f "/opt/userdata/startup-type" ]
then
  startup="$(cat /opt/userdata/startup-type)"
  if [ "DCS" = "$startup" ]
  then
    echo "dsc start-up: start gapp"
    startupLink="file:///opt/gira/share/devicestack/web/layout.html?g1=regular"
  elif [ "TastsensorX" = "$startup" ]
  then
    echo "tastsensorX start-up: start gapp"
    startupLink="file:///opt/gira/share/devicestack/web/layout.html?g1=regular"
  else
    echo "init start-up: start installation wizard"
    startupLink="file:///opt/gira/share/devicestack/web/layout.html?g1=regular"
  fi
else 
    echo "no startup found: start installation wizard"
    startupLink="file:///opt/gira/share/devicestack/web/layout.html?g1=regular"
fi

function start() {
echo ${starupLink}
    if [ ! -f ${PID_FILE} ]; then
        echo "1" > ${START_FLAG}
        sleep 5
        if [ -f ${START_FLAG} ]; then
          /usr/bin/g-watchdog ${startupLink} &
          echo $! > ${PID_FILE}
        else
          echo GAPP was stopeed
        fi
    else
        echo GAPP already running: `cat ${PID_FILE}`
    fi
}

function stop() {
    rm -f ${START_FLAG}
    /sbin/start-stop-daemon -K -n g-watchdog -p ${PID_FILE}    
    killall content_shell
    rm -f ${PID_FILE}
}

case "${CMD}" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo "usage: /opt/gira/bin/gapp {start|stop|restart}"
    ;;
esac
