#!/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

parameters="?locale=de-DE&ip=localhost&version="${IMAGE_VERSION}""


if [ -f "/opt/card/gira/demo/demo.sales" ]
then
    if [ -f "/opt/card/gira/demo/demo.sales.activated" ]
    then
        echo "start GiraApp in Demo Mode"
        /opt/gira/demo/sales/load_sequences
        startupLink="file:///opt/userdata/demo/sales/gapp/layout.html${parameters}&demomode=true"
    else
        echo "do nothing. system will be restarted. splash screen remains active"
    fi
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/userdata/gapp/layout.html${parameters}"
  elif [ "TastsensorX" = "$startup" ]
  then
    echo "tastsensorX start-up: start gapp"
    startupLink="file:///opt/userdata/gapp/layout.html${parameters}"
  else
    echo "init start-up: start installation wizard"
    startupLink="file:///opt/userdata/gapp/firstInstallationWizard.html${parameters}"
  fi
else 
    echo "no startup found: start installation wizard"
    startupLink="file:///opt/userdata/gapp/firstInstallationWizard.html${parameters}"
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
