#!/bin/sh

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars
SWDTD="/etc/init.d/swdtd"
CORES_PATH=/opt/userdata/cores
mkdir -p ${CORES_PATH}

case "$1" in
  start)
    ulimit -c unlimited >/dev/null 2>&1
    echo "${CORES_PATH}/core_pid-%e_sig-%s" > /proc/sys/kernel/core_pattern
    GDS_COUNT=$(ps | grep -c "${DEVICESTACK}")
    if [ "${GDS_COUNT}" -gt 1 ]
    then
      echo "[devicestack] Gira DeviceStack already running! Won't start again!"
      exit 0
    fi
    
    # Start dummy watchdog on developer packages
    # Will prevent reboots after killing the devicestack
    if [ -f "${DUMMY_WATCHDOGFILE}" ]
    then
      ${SWDTD} start
    fi
    
    # Check for commissioning mode
    if [ -f "${COMMISSIONED_FILE}" ]
    then
      echo -n "Starting DeviceStack ... "
      ${DEVICESTACK} &
      echo "$!" > "${DS_PIDFILE}"
      echo "$!"
      pid=""
      counter=3
      while [ "$pid" = "" ] && [ $counter -gt 0 ]
      do 
        pid=$(pidof devicestack)
        counter=$((counter-1))
        sleep 3
      done
      if [ "$pid" = "" ]
      then
         echo "No devicestack running. Rebooting."
         ${GDS_REBOOT}
      fi
    else
      echo -n "Starting DeviceStack in commissioning mode ... "
      COMMAND="${DEVICESTACK} -C"
      ${COMMAND} &
      echo "$!" > "${DS_PIDFILE}"
      echo "$!"
    fi
    ;;
  stop)
    echo -n "Stopping DeviceStack ... "
    if start-stop-daemon --stop --quiet --pidfile "${DS_PIDFILE}"
    then
      echo "done."
    else
      echo "failed."
    fi
    # Also terminate dummy watchdog if enabled
    if [ -f "${DUMMY_WATCHDOGFILE}" ]
    then
      ${SWDTD} stop
    fi
    ;;
  *)
    echo "Usage: $0 (start|stop)"
    exit 1
esac

exit 0
