#!/bin/sh

# this should be initialized in /etc/profile to remove the path dependency in the scripts:
. /opt/gira/bin/environment

# Starts a simple loop to check the configuration:
# If /tmp/enabledebug is present, the debug mode is activated
# If /tmp/disabledebug is present, the debug mode is deactivated

while [ 1 ]
do
  sleep 10;

  # Remove log message when accessing the UUID chip on im02 hardware that spams the system. Needs to be fixed properly.
  sed -e "/user.err kernel: i2c i2c-0: sendbytes: NAK bailout.$/d" -i /var/log/messages
  
  # check if we should enable extended debugging
  if [ -f "/tmp/enabledebug" ]; then
    rm -f /tmp/enabledebug
    logger -t "CONFIGDAEMON" "Activating debug mode..."
    sleep 5
    ${BINARYPATH}/enableextendedlogging.sh 1 &
  fi
  # check if we should disable extended debugging
  if [ -f "/tmp/disabledebug" ]; then
    rm -f /tmp/disabledebug
    logger -t "CONFIGDAEMON" "Deactivating debug mode..."
    sleep 5
    ${BINARYPATH}/enableextendedlogging.sh 0 &
  fi
  # check if we should auto-disable extended debugging
  if [ -f "${DEBUGACTIVE}" ]; then
    FILEDATE=`date -r /opt/userdata/.kimdebugmode +%s`
    NOWDATE=`date +%s`
    DIFFSECONDS=$(( ($NOWDATE) - ($FILEDATE) ))
    if [ $DIFFSECONDS -ge $DEBUGTIME ]; then
      logger -t "CONFIGDAEMON" "Auto-Deactivating debug mode..."
      ${BINARYPATH}/enableextendedlogging.sh 0 &
      sleep 5
    fi
  fi
  # check if we should reboot
  if [ -f "/tmp/rebootnow" ]; then
    # differ between old style and new style:
	if [ -f /opt/gira/bin/dscsampleapp ]; then
		# new style uses the mandatory dscsampleapp
		/opt/gira/bin/dscsampleapp -r='{"command":"Restart","type":"Device"}'
		sleep 15
		reboot -f
	else
		reboot -f
	fi
  fi
  # check if we perform a factory reset
  if [ -f "/tmp/factoryreset" ]; then
	# differ between old style and new style:
	if [ -f /opt/gira/bin/dscsampleapp ]; then
		# new style uses the mandatory dscsampleapp
		/opt/gira/bin/dscsampleapp -r='{"command":"Restart","type":"FactoryReset"}'
		sleep 15
		${BINARYPATH}/factory-reset
		sleep 5
		reboot -f
	else
		rm -f /tmp/factoryreset
		${BINARYPATH}/factory-reset
		sleep 5
		reboot -f
	fi
  fi
done
