#!/bin/bash

# set directory with tvheadend user data
homedir=$HOME

if [ $# -eq 1 ]; then
  homedir=$1
fi

cd $homedir/.hts/tvheadend/dvr/log

# some initial values
start_date=0
recording=0
current_date=`date +%s`
wake_date=$((current_date+172800))

# start CHECK THIS start
# set time NOT to shut down before next recording
# minimum time in seconds needed for consecutive shutdown AND startup
safe_margin_start=600

# set time to start up before next recording
# minimum time in seconds needed to start up the computer properly
safe_margin_startup=180
# end CHECK THIS end

# routine to find out start and stop running recording and next recording
for i in $( ls ); do
  tmp_start=`cat $i | grep '"start":' | cut -f 2 -d " " | cut -f 1 -d ","`
  tmp_stop=`cat $i | grep '"stop":' | cut -f 2 -d " " | cut -f 1 -d ","`
  tmp_start_extra=$((`cat $i | grep '"start_extra":' | cut -f 2 -d " " | cut -f 1 -d ","`*60))
  tmp_stop_extra=$((`cat $i | grep '"stop_extra":' | cut -f 2 -d " " | cut -f 1 -d ","`*60))

  # check for any running or almost running recording
  if [ $((tmp_stop+tmp_stop_extra)) -gt $((current_date)) -a $((tmp_start-tmp_start_extra-safe_margin_start)) -lt $((current_date)) ]; then
    recording=1
  fi

  # check for next recording and set wake up time
  if [ $((tmp_stop+tmp_stop_extra)) -gt $((current_date)) -a $((tmp_start-tmp_start_extra-safe_margin_start)) -gt $((current_date)) ]; then
    # take lower value (tmp_start or start_date)
    if [ $((start_date)) -eq 0 -o $((tmp_start-tmp_start_extra-safe_margin_start)) -lt $((start_date)) ]; then
      start_date=$((tmp_start-tmp_start_extra-safe_margin_start))
      wake_date=$((tmp_start-tmp_start_extra-safe_margin_startup))
      program_date=$((tmp_start))
    fi
  fi
done


# set wakeup time
if [ $((start_date)) -ne 0 ]; then
  SetRTCRestart $wake_date 
  reboot
fi

