#!/bin/bash
# -----------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2
#
# -----------------------------------------------------------------------
# adjust these variables to your personal needs
UPSOON=/var/cache/freevo/upsoon # choose path to freevo's upsoon file
PATHTONVRAM=/usr/sbin/ # path to the nvram-wakeup binary
# this should match the seconds until this script is executed again via cron 
CHECKINTERVAL=600 # seconds
# if this max. idle time (which this script is screening) is exceeded, system will shutdown
MAXIDLE=1200 # possible shutdown would be in $MAXIDLE + 1x$CHECKINTERVALL seconds 
# this variable should match the value of TV_RECORD_PADDING from your local_conf.py (or more sec)
RECORDPADDING=180 # seconds
# min. seconds between shutdown and next recording; if sec until next recording are less, no shutdown will be performed
SECUNTILSTART=900 # seconds
# does nvram-wakeup needs a reebot to function properly (0=no/1=yes)? 
NEED_REBOOT=1 # if set to 1 you need a section "PowerOff" in your lilo.conf 
# Assuming BIOS is set to UTC time, how many seconds have to be added/subtracted from your local time to reach UTC ?
UTCADJUST="- 3600" # for Germany which is UTC+1h the value has to be "- 3600"
# convert this to your language freevo is running with
# perform a "cat /var/cache/freevo/upsoon" to see what freevo outputs
SEARCHSTRING[1]="Today:"
SEARCHSTRING[2]="Tomorrow:"
SEARCHSTRING[3]="This.Week:"
STRING_AT="at" # e.g. "- Nameoftheshow at 12:00AM"
#                                      ^^

#######################################################################################################################
# normally there should be no need to edit anything beyond this row!

# tmp. files for this script
TMP_PS=/tmp/freevo/wakeup_ps 
TMP_IDLE=/tmp/freevo/wakeup_idle
# local for this script 
LANG="en"
# first time running this script ?
touch ${TMP_IDLE}
# maybe recordserver isn't running, no upsoon-file present
touch ${UPSOON}

# seconds to add for today, tomorrow, this week and in three days 
TOADD[1]=0
TOADD[2]=86400
TOADD[3]=172800
TOADD[4]=259200

typeset -i OTHERPS IDLE NEWIDLE HOUR TOADD WAKEUP MAXIDLE CHECKINTERVAL
# check if mplayer, xine, etc. is running
ps -Af  > ${TMP_PS}
OTHERPS=`egrep "\/[a-z]*\/(tvtime|xine|mplayer|mencoder|radio|xmms)" ${TMP_PS}|wc -l`
rm ${TMP_PS}
SHUTDOWN=0
if [ ${OTHERPS} -eq 0 -o "$1" == "shutdown" ]
then
	# no relevant process running, increase idle time
	NEWIDLE=`expr $(cat ${TMP_IDLE}|awk '{print $1}') + ${CHECKINTERVAL}`
	if [ ${NEWIDLE} -gt ${MAXIDLE} -o "$1" == "shutdown" ]
	then
		#  max. idle time exceeded, check for wakeup time and shutdown
		NOW=`date +%s`
		typeset -i i
		i=1
		for VAR in ${SEARCHSTRING[*]}
		do
			# we found a heading (today/tomorrow/this week) in upsoon, lets open it
			if grep "^${VAR}" ${UPSOON} &>/dev/null
			then
				ITEM=0
				# read the upsoon-file
				while read LINE
				do
					# approaching the heading...
					SHOW=`echo "${LINE}"|grep "^- "|wc -l`
					if echo "${LINE}"|grep "^${VAR}" &>/dev/null
					then
						ITEM=1
					# is there a valid entry in the heading ?
					elif [ ${SHOW} -eq 1 -a ${ITEM} -eq 1 ]
					then
						TIME=`echo ${LINE}|sed "s/- .* ${STRING_AT} //"`
						# check string [0-9][0-9]:[0-9][0-9][A/P]M if AM or PM
						if echo ${TIME}|grep "PM" 1>/dev/null
						then
							# add 12h if time is PM
							HOUR=`expr ${TIME:0:2} + 12`
						else
							HOUR=`expr ${TIME:0:2} + 0`
						fi
						MINUTES=${TIME:3:2}
						# this day/month is "wrong", will be corrected with $TOADD
						SCHEDULED="`date +%F` ${HOUR}:${MINUTES}:00"
						# this is the wakeup date in epoch notation
						WAKEUP=$(expr `date -u -d "${SCHEDULED}" +%s` + ${TOADD[${i}]} - ${RECORDPADDING} ${UTCADJUST})
						# is the start still in the future
						if [ "${WAKEUP}" -gt "${NOW}" ]
						then
							# we found a valid entry, leave loop 
							SHUTDOWN=1
							break 2
						fi
					# ooops, we left the valid section, seems as a new heading started
					elif [ ${SHOW} -eq 0 -a ${ITEM} -eq 1 ]
					then
						break
					fi
				done < ${UPSOON}
			fi
			# we need this count for $TOADD[4] only...
			i=$i+1
		done
		# no entry in upsoon found, check again in three days...
 		if [ ${SHUTDOWN} -eq 0 ]
		then
			WAKEUP=$(expr `date +%s` + ${TOADD[$i]} - ${RECORDPADDING} ${UTCADJUST})
		fi
		# set wakeup time in bios
		${PATHTONVRAM}/nvram-wakeup --directisa -s ${WAKEUP}
		# reset for next recording
		echo "0" > ${TMP_IDLE}
		DIFF=`expr $WAKEUP - $NOW`
		if [ ${DIFF} -lt ${SECUNTILSTART} ]
		then
			# time until next recording is less than $SECUNTILSTART
			if [ "$1" == "shutdown" ]
			then
				# if user wants to shutdown, just perform reboot; do nothing when running from cron
				/sbin/shutdown -r now
			fi
		else
			# it's time enough until next rec starts, please shutdown
			if [ ${NEED_REBOOT} -eq 0 ]
			then
				# nvram-wakeup doesn't needs a reboot 
				# perform shutdown now ! See you again at $WAKEUP. Good bye!
				/sbin/shutdown -h now
			else
				# lilo will boot system and immediately switch to runlevel 0
				/sbin/lilo -R PowerOff
				# perform reboot now ! See you again at $WAKEUP. Good bye!
				/sbin/shutdown -r now
			fi	
		fi
	else
		# increase idle time
		echo "${NEWIDLE}" > ${TMP_IDLE}
	fi
else
	# reset, still working
	echo "0" > ${TMP_IDLE}
fi