#!/bin/sh

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=$(cat /opt/extparam/booted_firmware_version)
if [ -z $IMAGE_VERSION ]
then
  source /etc/buildversion
fi

STARTUPLINK="file:///opt/gira/share/devicestack/web/layout.html?g1=regular"
if [ -f "/opt/card/gira/demo/demo.sales" ]
then
  printf "start GiraApp in Demo Mode\\n"
  STARTUPLINK="${STARTUPLINK}&demomode=true"
elif [ -f "/opt/userdata/startup-type" ]
then
  # Is this file even used anymore, or is it deprecated? They all start the same
  # thing anyways. --mgr
  STARTUP="$(cat /opt/userdata/startup-type)"
  if ! [ -z ${STARTUP+x} ]
  then
    printf "%s start-up: start gapp\\n" "${STARTUP}"
  else
    printf "no startup found: start installation wizard\\n"
  fi
else 
  printf "no startup found: start installation wizard\\n"
fi

start() {
  if [ ! -f "${PID_FILE}" ]
  then
    printf "1\\n" > "${START_FLAG}"
    sleep 5
    if [ -f "${START_FLAG}" ]
    then
      /usr/bin/g-watchdog ${STARTUPLINK} &
      printf "%s\\n" "$!" > "${PID_FILE}"
    else
      printf "GAPP was stopped\\n"
    fi
  else
    printf "GAPP already running: %s\\n" "`cat \"${PID_FILE}\"`"
  fi
}

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
    ;;
  *)
    printf "usage: /opt/gira/bin/gapp {start|stop|restart}\\n"
    ;;
esac
