#!/bin/sh

# Called by the backend to see if it's OK to shutdown

# 0 : Allows the box to reboot
# 1 : Sends the backend around the idle timeout period again
# 2 : Resets the "a client has connected" flag

# Manual stay awake
manual=0
if [ -e ~/stayawake ]; then
	manual=1
fi

# checks to see if any users are logged in
ssh=0
if last | head | grep -q "pts/.*still logged in"; then
	ssh=1
fi

# check if mythweb has been accessed
web=0
~myth/bin/check-mythweb.py
if [ $? -eq 1 ]; then
	web=1
fi

# Check if XBMC has been idle for >2 hours
idle=0
IDLEFILE=~/.xbmcidletime
if [ -r $IDLEFILE ]; then
  # Check the idlefile has been updated in the last 10 minutes
  lastmod=`stat -c %Y $IDLEFILE`
  now=`date +%s`
  if [ $(( $lastmod + 600 )) -gt $now ]; then
    idletime=`cat $IDLEFILE`
    if [ $idletime -gt 7200 ]; then
      idle=1
    fi
  fi
fi

# check if XBMC is running
xbmc=0
if ps axwww | grep -v grep | grep -q xbmc-standalone; then
  xbmc=1
fi

# Don't shutdown if manual override, SSH or web access
if [ $manual -eq 1 -o $ssh -eq 1 -o $web -eq 1 ]; then
  exit 1
fi

# If XBMC is running and it's not idle we can't shutdown
if [ $xbmc -eq 1 -a $idle -eq 0 ]; then
  exit 1
fi

