#!/bin/sh
EPGSCAN_VERS=20100307		# don't change, version will be checked out bei epgscan !!

# scanning the channels for epg in background
# no scan if last successful scan was before less than scan_wait_hours 
# no scan if vdr is recording
# no scan if time untill next timer recording not reach for epg scan
# actualization of search timers after successful scan
# wakeup vdr from standby if there is enough time for scanning epg before next timer recording
# configuration of "scan only from standby" may ensure that no vdr client is using a tuner
# shut down back to standby if awoke
# verbose logging for debugging 

# epgscan.sh [-a]
 
#option -a (abort scan) is only usefull by manual starts of this script. Don't use it by start in crontab.
# With this option a second start while the scan is running, 
# will abort a running scan by deleting the flag file. 

# Attention this script code must start with shebang #!/bin/sh  if it runs with #!/bin/bash the scan loop aborts 

# author: Klaus Sust   nickname: broetlibahn
# support and newest version to be found at reelbox-forum : 
# http://reelbox-forum.com/showpost.php?p=136397&postcount=1


# ------------------------ internal function only in this script ------------------------------------
msg() { 
# msg "text" [n]
# n = number 0, 1, 2  : message is displayed if variable DISP_MSG >= n

# this function displays a message at the frontdisplay of tne reelbox and on the mediacenter tv-screen          
	c=1

	if [ $# -gt 1 ]; then c=$2; fi
	if [ $DISPL_MSG -ge $c ]; then $COMMAND MESG "EPG_Scan: $1" > /dev/null 2>&1; fi 
	}
	
# -------------------internal function in both scripts but different ---------------------

log() { 
# log "text" [-t|-d]
# option -t does not write the timestamp  -d = only writes an entry when VERBOSE_LOG = 1
	if [ $DISPL_LOG -gt 0 ]; then echo " $1"; fi 		# for debuging display log entries at the console too

# this function writes text into the logfile
	if [ $# -gt 1 ]; then
		case "$2" in
			-t) echo "$1" >> $LOG_FILE  2>&1;;
			-d) if [ $VERBOSE_LOG -gt 0 ]; then echo "$(date +%y%m%d" "%T) $1" >> $LOG_FILE  2>&1; fi;;
			 *) echo "$(date +%y%m%d" "%T) $1" >> $LOG_FILE  2>&1;;
		esac
		return
	fi
	echo "$(date +%y%m%d" "%T) $1" >> $LOG_FILE  2>&1
	}

# ------------------- internal functions equal in both scripts  ------------------------------------

log_header()  {
# log_header
# this function writes a header into the logfile. if epgscan is in debuging mode it writes the configuration too
	log "epgscan script $EPGSCAN_VERS creates log file"
	log " " -t
	log "# EPGSCAN_VERS=$EPGSCAN_VERS, FP_TIMER_VERS=$FP_TIMER_VERS, CONF_VERS=$CONF_VERS" -t 
	log " " -t
	log "# user configuration" -t
	log "# CHANNEL_GROUPS=$CHANNEL_GROUPS" -t 
	log "# GROUP1_FIRST_CHANNEL=$GROUP1_FIRST_CHANNEL, GROUP1_LAST_CHANNEL=$GROUP1_LAST_CHANNEL" -t
	log "# GROUP2_FIRST_CHANNEL=$GROUP2_FIRST_CHANNEL, GROUP2_LAST_CHANNEL=$GROUP2_LAST_CHANNEL" -t 
	log "# GROUP3_FIRST_CHANNEL=$GROUP3_FIRST_CHANNEL, GROUP3_LAST_CHANNEL=$GROUP3_LAST_CHANNEL" -t
	log "# " -t
	log "# DAILY_SCANS=$DAILY_SCANS, DAILY_SCAN1=$DAILY_SCAN1, DAILY_SCAN2=$DAILY_SCAN2" -t
	log "# DAILY_SCAN_TRY_AGAIN_M=$DAILY_SCAN_TRY_AGAIN_M, DAILY_SCAN_WAIT_M=$DAILY_SCAN_WAIT_M" -t 
	log "# DAILY_SCAN_ONLY_STB=$DAILY_SCAN_ONLY_STB, DSTB_AFTER_SCAN=$DSTB_AFTER_SCAN" -t 
	log "# " -t
	log "# SCAN_MODE=$SCAN_MODE, SCAN_TIME_S=$SCAN_TIME_S" -t 
	log "# DISPL_MSG=$DISPL_MSG, DISPL_LOG=$DISPL_LOG, VERBOSE_LOG=$VERBOSE_LOG, KEEP_LOG=$KEEP_LOG" -t
	if  [ $VERBOSE_LOG -gt 0 ]; then
		log " " -t
		log "# internal configuration" -t
		log "# boot_s=$BOOT_S, rec_dist_s=$REC_DIST_S" -t 
		log "# event_timeout_m=$EVENT_TIMEOUT_M, request_shut_down=$REQUEST_SHUT_DOWN (0=request, 1=standby, 2=deepstandby)" -t 
		log " " -t
		log "# FLG_FILE=$FLG_FILE" -t 
		log "# LOG_FILE=$LOG_FILE" -t
		log "# TEMP_FILE=$TEMP_FILE" -t 
		log "# FP_FILE=$FP_FILE" -t
		log "# EPGSCAN_SCRIPT=$EPGSCAN_SCRIPT" -t 
		log "# FP_SCRIPT=$FP_SCRIPT" -t
		log " " -t
		log "# STB_FILE=$STB_FILE" -t 
		log "# WAKE_FILE=$WAKE_FILE" -t
		log "# REC_FILE=$REC_FILE" -t 
		log "# REELVDRD_FILE=$REELVDRD_FILE" -t
		log "# VDR_SETUP_CONF_FILE=$VDR_SETUP_CONF_FILE" -t
		log "# CRON_FILE=$CRON_FILE" -t 
		log "# CRON_SEARCH=$CRON_SEARCH" -t
		log " " -t
		log "# crontab entries" -t
		log "# mm hh  (day month day_of_week)  user  command    # commentary" -t
		log " " -t
		CRONTAB=$(grep "epgscan.sh" $CRON_FILE) 2>/dev/null
		log "$CRONTAB" -t
		log " " -t
	fi
	log " " -t
	} 
	
count_channels() {

	if [ $CHANNEL_GROUPS -gt 0 ];then
		if [ $GROUP1_LAST_CHANNEL -le $GROUP1_FIRST_CHANNEL ]; then
			log "configuration error: GROUP1_FIRST_CHANNEL=$GROUP1_FIRST_CHANNEL is not lower GROUP1_LAST_CHANNEL=$GROUP1_LAST_CHANNEL" 
			exit_shut_down
		fi
		CHANNELS=$(( $GROUP1_LAST_CHANNEL - $GROUP1_FIRST_CHANNEL + 1))
		MAX_CHANNEL_NO=$GROUP1_LAST_CHANNEL 
		if [ $CHANNEL_GROUPS -gt 1 ];then
			if [ $GROUP1_LAST_CHANNEL -gt $GROUP2_FIRST_CHANNEL ]; then
				log "configuration error: GROUP2_FIRST_CHANNEL=$GROUP2_FIRST_CHANNEL is lower GROUP1_LAST_CHANNEL=$GROUP1_LAST_CHANNEL" 
				exit_shut_down
			fi
			if [ $GROUP2_LAST_CHANNEL -le $GROUP2_FIRST_CHANNEL ]; then
				log "configuration error: GROUP2_FIRST_CHANNEL=$GROUP2_FIRST_CHANNEL is not lower GROUP2_LAST_CHANNEL=$GROUP2_LAST_CHANNEL" 
				exit_shut_down
			fi
			CHANNELS=$(( $CHANNELS + $GROUP2_LAST_CHANNEL - $GROUP2_FIRST_CHANNEL + 1))
			MAX_CHANNEL_NO=$GROUP2_LAST_CHANNEL
			
			if [ $CHANNEL_GROUPS -gt 2 ];then
				if [ $GROUP2_LAST_CHANNEL -gt $GROUP3_FIRST_CHANNEL ]; then
					log "configuration error: GROUP3_FIRST_CHANNEL=$GROUP3_FIRST_CHANNEL is lower GROUP2_LAST_CHANNEL=$GROUP2_LAST_CHANNEL" 
					exit_shut_down
				fi
				if [ $GROUP3_LAST_CHANNEL -le $GROUP3_FIRST_CHANNEL ]; then
					log "configuration error: GROUP3_FIRST_CHANNEL=$GROUP3_FIRST_CHANNEL is not lower GROUP3_LAST_CHANNEL=$GROUP3_LAST_CHANNEL" 
					exit_shut_down
				fi
				CHANNELS=$(( $CHANNELS + $GROUP3_LAST_CHANNEL - $GROUP3_FIRST_CHANNEL + 1))
				MAX_CHANNEL_NO=$GROUP3_LAST_CHANNEL
			fi
		fi
	fi
}

inrange_utc() {
# inrange_utc date [n] [-s | +s | -m | +m | -h | +h | -d | +d]
# date = utc date in seconds  n = range s = seconds, m = minutes, h = hours, d = days
# prefix - = the range is in the past, before now, + = tehe range is in the future, after now
# this function checks if variable date is utc time and in range of + or - n  from now

	if [ -z "$1" ]; then return 1; fi  # parameter date missing
	
	if [ -n "$2" ] && [ -n "$3" ]; then 
		PREFIX=$(expr substr "$3" 1 1)
		case "$3" in
			-s|+s) RANGE_S=$2;;
			-m|+m) RANGE_S=$(($2*60));;
			-h|+h) RANGE_S=$(($2*3600));;
			-d|+d) RANGE_S=$(($2*216000));;
			*) return 1 ;;
		esac
	else 
	return 1
	fi
		
	if date -d @$1 +%s > /dev/null 2>&1; then  					# $1 is valid utc date
		case "$PREFIX" in
			-) if [ $1 -gt $(($NOW_UTC-$RANGE_S)) ] && [ $1 -lt $NOW_UTC ]; then echo; return 0; fi;; # in range before now
			+) if [ $1 -gt $NOW_UTC ] && [ $1 -lt $(($NOW_UTC+$RANGE_S)) ]; then echo; return 0; fi;; # in range after now
		esac
	fi
	return 1   # date is unvalid or out of range
	}

init_crontab() {
# inserts cronjobs in the crontab file which will start epgscan 
# it must be in epgscan_fp because changes in the configuration file will be actualized each going deep standby  
# this function must be in epgscan to initilize the crontab when the vdr is not going into deep standby
	CRON_JOB_EXIST=0
	if grep -q "$CRON_SEARCH" $CRON_FILE; then
		CRON_JOB_EXIST=1													# entry found in crontab
	else
		log "no epgscan job found in crontab" -d
	fi		

	if [ $CRON_JOB_EXIST -eq 0 ] || [ "$NEW_CRON" != "$OLD_CRON" ]; then		# no entry in crontab or configuration has changed
		log "daily_scans are new or changed in configuration file" -d
		if [ $CRON_JOB_EXIST -gt 0 ]; then
			sed -i /"$CRON_SEARCH/d" $CRON_FILE 2>/dev/null  						# delete old cron jobs
			log "old  jobs: $OLD_CRON" 
			log "delete old cron jobs" -d
		fi
		
		if [ $DAILY_SCANS -gt 0 ]; then										# write jobs for daily scans into crontab
			echo "#	inserted from epgscan.sh - comments are identifiers, don't change!		author: broetlibahn" >> $CRON_FILE 2>/dev/null
			log "cron jobs: $NEW_CRON"										# save cron jobs to detect if they have been changed
			COMMENT="#  daily epgscan	author: broetlibahn"
			CRON1="$DAILY1_MM $DAILY1_HH	* * *	root	$EPGSCAN_SCRIPT	$COMMENT"
			echo "$CRON1"  >> $CRON_FILE 2>/dev/null							# entry for daily scan 1
			log "add cron job: $CRON1" -d 
			if [ $DAILY_SCANS -gt 1 ]; then
				if [ ! $DAILY1_HHMM -lt $DAILY2_HHMM ]; then 
					log "configuration error: daily_scan2 ignored because greater than daily_scan1"
				else
					CRON2="$DAILY2_MM $DAILY2_HH	* * *	root	$EPGSCAN_SCRIPT	$COMMENT" 
					echo "$CRON2"  >> $CRON_FILE 2>/dev/null							# entry for daily scan 2
					log "add cron job: $CRON2" -d
				fi
			fi
		fi
	fi
	}

# --------------- internal functions only for this script -----------------------------

try_later() {
# set the next daily scan time utc in timer file for daily scan to the next full or half hour
	if [ $IS_DAILY_SCAN -gt 0 ] && [ $DAILY_SCAN_TRY_AGAIN_M -gt 0 ]; then			# is a daily scan and shall try again
		if [ $DAILY_SCAN_TRY_AGAIN_M -gt 60 ]; then
			log "configuration error: DAILY_SCAN_TRY_AGAIN_M > 60"
			DAILY_SCAN_TRY_AGAIN_M=60													# set try again in 60 minutes
		elif [ $DAILY_SCAN_TRY_AGAIN_M -lt 10 ]; then
			log "configuration error: DAILY_SCAN_TRY_AGAIN_M < 10"
			DAILY_SCAN_TRY_AGAIN_M=10													# set try again in 60 minutes
		fi
		NEXT_TRY_UTC=$(( $NOW_M_UTC + $DAILY_SCAN_TRY_AGAIN_M * 60 ))				# now + wait Minutes minutes
		NEXT_DS_BEFORE_UTC=$(( $NEXT_TRY_UTC + 60 + $DAILY_SCAN_WAIT_M * 60 ))		# if next daily scan is before this time: stop try later
		
		# find next daily scan 
		if [ $NOW_HHMM -lt $DAILY1_HHMM ]; then
			NEXT_DAILY_SCAN_UTC=$(( $TODAY_UTC + $DAILY1_S ))					# daily_scan1 todays
		elif [ $DAILY_SCANS -gt 1 ] && [ $DAILY1_HHMM -lt $DAILY2_HHMM ] && [ $NOW_HHMM -lt $DAILY2_HHMM ]; then # Scan 1 is before Scan 2
				NEXT_DAILY_SCAN_UTC=$(( $TODAY_UTC + $DAILY2_S ))				# daily_scan2 todays
			else
				NEXT_DAILY_SCAN_UTC=$(( $TODAY_UTC + $DAILY1_S + 86400))		# daily_scan1 tomorrow
		fi
		log "try again at $(date -d @$NEXT_TRY_UTC +%R) if next daily scan $(date -d @$NEXT_DAILY_SCAN_UTC +%R) is not before $(date -d @$NEXT_DS_BEFORE_UTC +%R)" -d  
		if [ $NEXT_DS_BEFORE_UTC -lt $NEXT_DAILY_SCAN_UTC ]; then
			NEXT_TRY_MM=$(date -d @$NEXT_TRY_UTC +%M )			# the minutes of the next try hour
			NEXT_TRY_MM=$(echo $NEXT_TRY_MM | awk '{print $1 + 0}')				# remove leading zeros
			echo "$NEXT_TRY_UTC = $(date -d @$NEXT_TRY_UTC +%y%m%d" "%R)" > $FP_FILE 2>/dev/null				# write next try to fp_timer_file
			log "next scan try at: $(date -d @$NEXT_TRY_UTC +%y%m%d" "%R)" 
			CRON1="$NEXT_TRY_MM *	* * *	root	$EPGSCAN_SCRIPT	$COMMENT_TRY_LATER"
			echo "$CRON1"  >> $CRON_FILE 2>/dev/null							# entry for try later daily scan
			log "add cron job: $CRON1" -d
		else
			log "next daily scan at: $(date -d @$NEXT_DAILY_SCAN_UTC +%y%m%d" "%R)" 
		fi
	fi
	}
	
init_reelvdrd() {
	# insert a call for the script next_epgscan.sh to change the wakeup time 
	# before reelvdrd writes it into the frontpanel timer
	# this wakes the vdr for the next daily epg scan without needing a record timer in vdr
	SEARCH="broetlibahn"
	if [ -e $FP_SCRIPT ]; then	# script exists
		chmod +x $FP_SCRIPT > /dev/null 2>&1 		# executable the script
	else
		log "error: missing script: $FP_SCRIPT"
		if grep -q "$SEARCH" $REELVDRD_FILE; then
			log "delete old epgscan entries in reelvdrd" 
			sed -i /"$SEARCH/d" $REELVDRD_FILE 2>/dev/null  						# delete old entries
		fi
		return
	fi
	
	COMMENT="daily epgscan author: broetlibahn"
	
	if grep -q "$SEARCH" $REELVDRD_FILE; then
	:		# do nothing
	else
		USED_VAR=$(grep -m1 "\-wakeup" $REELVDRD_FILE | tr -d "\t" | tr -s " " | tr -d "\"" | cut -f3 -d " " | cut -c 2- )
		INSERT="$USED_VAR=\$($FP_SCRIPT \$$USED_VAR) # $COMMENT"
		TEXT1="  the next line was inserted to change the wakeuptime for the next $COMMENT\n"
		sed -i "/-wakeup/i\#	$TEXT1\	$INSERT\n" $REELVDRD_FILE
		log "insert in reelvdrd: $USED_VAR=\$($FP_SCRIPT \$$USED_VAR)"  
	fi
	}

check_nextrec() {
	# check if there is enough time for epgscan until nextrec_utc 
	if date  -d @$NEXTREC_UTC +%s > /dev/null 2>&1; then  		# is valid utc date
		NEXTREC_M=$((($NEXTREC_UTC-$(date +%s))/60))
		NEXTREC=$(date -d @$NEXTREC_UTC +%y%m%d" "%R)
		
		log "next record: $NEXTREC_UTC (utc) = $NEXTREC in $NEXTREC_M minute(s)" -d

		if [ $NEXTREC_M -lt 0 ] && [ $NEXTREC_M -gt -30 ]; then
			log "recording possible just started"
#r			msg "kein Scan, da Aufnahme startet " 2
#r			try_later		# try again at next full or half hour
#r			rm $FLG_FILE  > /dev/null 2>&1
#r			log "epgscan script finished without scan"
#r			exit 1
		fi

		if (inrange_utc $NEXTREC_UTC $NEED_TIME_S +s); then 	# valid timer in range of + needed seconds from now  
															# ignore past timers ( when a record is running is this the timer of the actual record )
			if [ $VERBOSE_LOG -eq 0 ]; then
				log "next vdr record timer at $NEXTREC in only $NEXTREC_M minute(s)" 
			fi
			log "not enough time until next record, $NEED_TIME_M minutes needed for scan" -d
#r			msg "kein Scan, Aufnahme in $NEXTREC_M m"
#r			try_later		# try again if daily scan at next full or half hour
#r			rm $FLG_FILE  > /dev/null 2>&1
#r			log "epgscan script finished without scan"
#r			exit 1
		fi
	else
		log "no valid record timer found" -d
	fi
	}
	
start_log() {
	log " " -t
	if [ $ABORT_SCAN -gt 0 ]; then
		MANUAL="manually"
	fi
	if  [ $SCAN_MODE -gt 0 ]; then
		log "epgscan.sh script $EPGSCAN_VERS $MANUAL in streaming mode started" 
	else
		log "epgscan.sh $1 script version $EPGSCAN_VERS $MANUAL in vdr front zapping mode started" 
		if [ $SCAN_TIME_S -lt 5 ]; then
			log "in zapping mode SCAN_TIME_S=$SCAN_TIME_S minimum 5 seconds needed" 
			SCAN_TIME_S=5
		fi
	fi
	if [ $DISPL_LOG -gt 0 ] && [ $SCAN_MODE -gt 0 ]; then
		log "DISPL_LOG=$DISPL_LOG configured for debugging at the console"
	fi
	}
	
exit_shut_down() {
# removes flagfile, exit the script 
# if awoke shut down to standby or deep standby

	if [ $NEXTREC_UTC -gt 0 ]; then
		NEXTREC_M=$((($NEXTREC_UTC-$(date +%s))/60))
	else 
		NEXTREC_M=1000
	fi
###########################################
#  for debugging of shut down only	#######
#	NEXTREC_M=3						#######
#	FP_WAKEUP=1						#######
#	STB=0							#######
#	DSTB_AFTER_SCAN=0				#######
#	REQUEST_SHUT_DOWN=0				#######
#	log "test: nextrec in $NEXTREC_M m, fp wakeup: $FP_WAKEUP, STB: $STB, DSTB_AFTER_SCAN: $DSTB_AFTER_SCAN, REQUEST_SHUT_DOWN: $REQUEST_SHUT_DOWN" ####
###########################################
	
				# remove flag file 
	
	if [ ! $CH_COUNTER -eq $CHANNELS ]; then                                   #r
		log "epgscan script aborted - channels"                            #r
		if [ -e $FLG_FILE ]; then rm $FLG_FILE  > /dev/null 2>&1; fi       #r
                exit                                                               #r
	fi                                                                         #r

	if [ ! -e $FLG_FILE ]; then                                                #r
		log "epgscan script aborted - flagfile"                            #r
                exit                                                               #r
	fi                                                                         #r

	if [ $FP_WAKEUP -eq 0 ] && [ $STB -eq 0 ]; then						# vdr was active before epgscan
		log "epgscan script finished from active vdr"
		if [ -e $FLG_FILE ]; then rm $FLG_FILE  > /dev/null 2>&1; fi
                exit
	fi
	



	NO_TIME=0
	if [ $FP_WAKEUP -gt 0 ] || [ $DSTB_AFTER_SCAN -gt 0 ] || [ $REQUEST_SHUT_DOWN -eq 2 ]; then		# awoke by frontpanel timer or deep standby wanted
#r		if [ $REQUEST_SHUT_DOWN -eq 1 ]; then 				# shut down mode = standby without request
#r			log "no deep standby possible: vdr request shut down mode = standby" -d 
#r		else
#r			if [ $NEXTREC_M -le $BOOT_M ]; then
#r				log "next record starts in $NEXTREC_M minute(s), no time for deep standby" -d
#r				NO_TIME=1
#r				if [ $REQUEST_SHUT_DOWN -eq 2 ]; then 				# shut down mode = deep standby without request
#r					log "no standby possible: vdr request shut down mode = deep standby" -d 
#r					log "epgscan script finished"
#r					exit											# if no time don't shut down
#r				fi
#r			else
#r				case "$REQUEST_SHUT_DOWN" in
#r					0)	log "shut down vdr to deep standby" -d; msg "DeepStandby-Abfrage in 30 s!" 0;;
#r					2)	log "shut down vdr without request to deep standby" -d; msg "DeepStandby direkt in 30 s!" 0;;
#r				esac
#r				sleep 30												# let time for search timer actualization
#r				$COMMAND HITK Power > /dev/null 2>&1
#r				if [ $REQUEST_SHUT_DOWN -eq 0 ]; then						# shut down mode = request before shut down
#r					$COMMAND HITK Down > /dev/null 2>&1
#r					sleep 7
#r					$COMMAND HITK Ok > /dev/null 2>&1
#r					if [ $NEXTREC_M -le $EVENT_TIMEOUT_M ]; then	# next record is before minimal event timeout 
#r						log "next record in $NEXTREC_M minutes, continue after request message" -d
#r						sleep 2												# wait for message record starts soon
#r						$COMMAND HITK Ok > /dev/null 2>&1					# quit message
#r					fi
#r				fi
#r				log "epgscan script finished"
#r				exit
#r			fi
#r		fi
		log "shut down vdr with request to standby" -d; msg "Standbyabfrage in 30 s!" 0
		sleep 30												# let time for search timer actualization
		$COMMAND HITK Power > /dev/null 2>&1
		sleep 7
		$COMMAND HITK Ok > /dev/null 2>&1
		log "epgscan script finished - standby"
	else    log "epgscan script finished - no standby"
        fi

															# awoke from standby or if deep standby not possible
#r	if [ $NEXTREC_M -le 2 ]; then
#r		if [ $NO_TIME -eq 0 ]; then
#r			log "next record starts in $NEXTREC_M minute(s), no time for standby" -d
#r		else
#r			log "no time for standby" -d
#r		fi
#r	else
#r		case "$REQUEST_SHUT_DOWN" in
#r			0) log "shut down vdr to standby" -d; msg "Standby-Abfrage in 30 s!" 0;;
#r			1) log "shut down vdr without request to standby" -d; msg "Standby direkt in 30 s!" 0;;
#r		esac
#r
#r		sleep 30													# let time for search timer actualization
#r		$COMMAND HITK Power  > /dev/null 2>&1
#r		if [ $REQUEST_SHUT_DOWN -eq 0 ]; then						# shut down mode = request before shut down
#r			sleep 7
#r			$COMMAND HITK Ok > /dev/null 2>&1
#r			if [ $NEXTREC_M -le $EVENT_TIMEOUT_M ]; then	# next record is before minimal event timeout
#r				log "next record in $NEXTREC_M minutes, continue after request message" -d
#r				sleep 2												# wait for message record starts soon
#r				$COMMAND HITK Ok > /dev/null 2>&1					# quit message
#r			fi
#r		fi
#r	fi
	if [ -e $FLG_FILE ]; then 
           rm $FLG_FILE  > /dev/null 2>&1
	else    
           log "finished but flagfile was deleted by other instance of script"
        fi
        exit 
	}

channel_scan_loop() {						# scan a group of channels
GROUP=$1
CHNR=$2
LAST_CHANNEL=$3

TIMEOUT_S=$(( $SCAN_TIME_S * 3 ))										# after this time wget will abort if no connection
log "scan group $GROUP: channel $CHNR to $LAST_CHANNEL" -d
msg "Gruppe $GROUP: Kanal $CHNR - $LAST_CHANNEL" 2
	while [ $CHNR -le $LAST_CHANNEL ]
	do
		CH_COUNTER=$(( $CH_COUNTER + 1 ))
		msg "Kanal $CHNR" 3
		if [ $VERBOSE_LOG -gt 1 ]; then log "counter=$CH_COUNTER, scan group $GROUP channel $CHNR" -d; fi
		if [ $SCAN_MODE -gt 0 ]; then							# scanning in background with the straeming server
			
			if [ $DISPL_LOG -gt 1 ]; then												# testing at console

				wget -T$TIMEOUT_S -O /dev/null http://$STREAMHOST:3000/PES/$CHNR 2>&1 &		# verbose on console output
				WPID=$!
				RET=$?
			else
				wget -q -T$TIMEOUT_S -O /dev/null http://$STREAMHOST:3000/PES/$CHNR 2>&1 &		# quiet
				WPID=$!
				RET=$?
			fi
			sleep $SCAN_TIME_S
			if [ $VERBOSE_LOG -gt 2 ]; then log "wget returned=$RET PID=$WPID" -d; fi
			kill $WPID
			RET=$?
			if [ $VERBOSE_LOG -gt 2 ]; then log "kill returned=$RET PID=$WPID" -d; fi
		else														# scanning in front by switching vdr
			$COMMAND CHAN $CHNR > /dev/null 2>&1
			sleep $SCAN_TIME_S
			if [ $VERBOSE_LOG -gt 1 ]; then log "scan channel $CHNR done" -d; fi
		fi
		if [ ! -e $FLG_FILE ]; then
			LAST_SCANNED_CHANNEL=$CHNR
			log "scan loop aborted (flag file missing) in group $GROUP after channel $CHNR "
			msg "wurde abgebrochen" 
			return 1
		fi
		CHNR=$(($CHNR + 1))

	done
	LAST_SCANNED_CHANNEL=$(($CHNR - 1))
	return 0
	}

# ========================= START ======================================

# -------------- include configuration from configuration file: ---------------------------------

# the configuration file epgscan.conf must be in the same directory with this script 

OWN_PATH=$0								# path and name to this script
OWN_PATH=${OWN_PATH%%epgscan.sh*}		# cut of own name
CONF_FILE="${OWN_PATH}epgscan.conf"		# add name of configuration file
NEED_CONF=20090921						# needed version of epgscan.conf
NEED_FP=20090921

if [ -f $CONF_FILE ]; then 
	. $CONF_FILE						# include all variables of the configuration file
else 
	echo "configuration file missing"
	exit 1
fi

if [ $CONF_VERS -lt $NEED_CONF ]; then
	log " " -t
	log "error: $EPGSCAN_VERS old version of epgscan.conf: $CONF_VERS needed: $NEED_CONF"
	echo "old version of configuriation file: $CONF_VERS needed $NEED_CONF"
	log "epgscan script finished without scan"
	exit 1
fi

if [ $DEACTIVATE_SCAN -gt 1 ]; then
	echo "epgscan is deactivated in configuration file "
	exit 1
fi

# --------------------------------- get some other informations ------------------------------------



NEW_CRON="$DAILY_SCANS;$DAILY_SCAN1;$DAILY_SCAN2"

#------------------- some needed time variables for time calculations --------------------------

NOW_UTC=$(date +%s)
NOW_M_UTC=$(( $NOW_UTC - $NOW_UTC % 60 )) 			# now at begin of actual minute
TODAY=$(date +%y%m%d)
TODAY_UTC=$(date -d "$TODAY" +%s) 
NOW_HHMM=$(date -d @$NOW_UTC +%R | tr -d ":" )
NOW_HHMM=$(echo $NOW_HHMM | awk '{print $1 + 0}')	# remove leading zeros
NOW_MM=$(date -d @$NOW_UTC +%M) 				# now minutes

STREAMHOST="127.0.0.1"    # IP of localhost
COMMAND=svdrpsend.sh

ABORT_SCAN=0
if [ $# -gt 0 ] && [ $1 = "-a" ]; then ABORT_SCAN=1; fi # only manual call will abort running scan

FP_TIMER_VERS=0
	if [ -e $FP_SCRIPT ]; then
		FP_TIMER_VERS=$(grep -m1 "^FP_TIMER_VERS=" $FP_SCRIPT | tr -d "\t" | tr -d " " | tr -d "\"" | tr -d "\"" | cut -f2 -d "=" | cut -f1 -d "#") 2>/dev/null
		if [ $FP_TIMER_VERS -lt $NEED_FP ]; then
			log " " -t
			log "error: old version of $FP_SCRIPT: $FP_TIMER_VERS needed: $NEED_FP"
			echo "old version of $FP_SCRIPT: $FP_TIMER_VERS needed $NEED_FP"
			log "epgscan script finished without scan"
			exit 1
		fi
		
	fi



# --------------------------- begin of equal initial part in both scripts -------------------------

if [ -e $MVDRSHUTDOWN_FILE ]; then				# vdr shutdown script where get the boot time from
	BOOT_S=$(grep -m1 "^BOOTTIME=" $MVDRSHUTDOWN_FILE | tr -d " " | cut -f2 -d "=" | cut -f1 -d "#") 2>/dev/null
else
	BOOT_S=300
fi
BOOT_M=$(($BOOT_S / 60))
BOOT_S=$(echo $BOOT_S | awk '{print $1 + 0}')		# remove leading zeros
BOOT1_S=$(( $BOOT_S + 120 )) 						# give 2 minute more for detecting daily scan

if [ -e $VDR_SETUP_CONF_FILE ]; then				# vdr setup configuration where get the MinEventTimeout from
	EVENT_TIMEOUT_M=$(grep -m1 "^MinEventTimeout" $VDR_SETUP_CONF_FILE | tr -d " " | cut -f2 -d "=" ) 2>/dev/null 
	EVENT_TIMEOUT_M=$(echo $EVENT_TIMEOUT_M | awk '{print $1 + 0}')	# remove leading zero for dec calculations
    REQUEST_SHUT_DOWN=$(grep -m1 "^RequestShutDownMode" $VDR_SETUP_CONF_FILE | tr -d " " | cut -f2 -d "=" ) 2>/dev/null 
	REQUEST_SHUT_DOWN=$(echo $REQUEST_SHUT_DOWN | awk '{print $1 + 0}')	# remove leading zero for dec calculations
else
	EVENT_TIMEOUT_M=20
	REQUEST_SHUT_DOWN=0
fi

# boot time in seconds needed from wakeup out of deep standby until vdr is running 
# the wakeup time in frontpanel timer will be daily scan less this minutes
# this time is also used to detect a daily scan 

	if [ $DAILY_SCANS -gt 0 ]; then
		DAILY1_MM="${DAILY_SCAN1##*:}"
		DAILY1_MM=$(echo $DAILY1_MM | awk '{print $1 + 0}')	# remove leading zero for dec calculations
		DAILY1_HH=${DAILY_SCAN1%%:*}
		DAILY1_HH=$(echo $DAILY1_HH | awk '{print $1 + 0}')	# remove leading zero for dec calculations
		DAILY1_HHMM=$(echo "$DAILY_SCAN1" | tr -d ":")
		DAILY1_HHMM=$(echo $DAILY1_HHMM | awk '{print $1 + 0}')	# remove leading zero for dec calculations
		DAILY1_S=$(( $DAILY1_HH * 3600 + $DAILY1_MM * 60 ))
		
		if [ $DAILY_SCANS -gt 1 ]; then
			DAILY2_MM="${DAILY_SCAN2##*:}"
			DAILY2_MM=$(echo $DAILY2_MM | awk '{print $1 + 0}')	# remove leading zero for dec calculations
			DAILY2_HH=${DAILY_SCAN2%%:*}
			DAILY2_HH=$(echo $DAILY2_HH | awk '{print $1 + 0}')		# remove leading zero for dec calculations
			DAILY2_HHMM=$(echo "$DAILY_SCAN2" | tr -d ":")
			DAILY2_HHMM=$(echo $DAILY2_HHMM | awk '{print $1 + 0}')	# remove leading zero for dec calculations
			DAILY2_S=$(( $DAILY2_HH * 3600 + $DAILY2_MM * 60 ))
		fi
	fi
	
	
	
	
# create log file if not exist
	if [ ! -e $LOG_FILE ]; then log_header; fi

# ---------------------- some checks if the scan is allowed to run  --------------------

CHANNELS=0
MAX_CHANNEL_NO=0							# max channel number
count_channels								# count the number of channels of all channel groups

OLD_CRON_EXIST=0
OLD_CRON="no saved cron entry"
OLD_CRON_ENTRY=$(tac $LOG_FILE |grep -m1 "cron jobs: " | tr -s " ") 2>/dev/null
	if [ -n "$OLD_CRON_ENTRY" ]; then
		OLD_CRON=${OLD_CRON_ENTRY##*jobs: }
		OLD_CRON_EXIST=1
	fi
	
# --------------------------- end of equal initial part in both scripts -------------------------

NEED_TIME_S=$(( $CHANNELS * $SCAN_TIME_S + $REC_DIST_S ))
NEED_TIME_S=$(( $NEED_TIME_S + 60 - ($NEED_TIME_S % 60) ))			# add time up to a whole minutes
NEED_TIME_M=$(( $NEED_TIME_S / 60 ))



NEXTREC_M=999
NEXTREC=" "
NEXTREC_UTC=0
KEEP_LOG_ERROR=0		# keep log because error

# start twice of this script may aborts running EPG-Scan if wanted.
# only needed if EPG-Scan is called by remote control
	if [ -e $FLG_FILE ]; then
		if [ $ABORT_SCAN -gt 0 ]; then
			msg "Abbruch eines laufenden Scan" 0
			log "! manually abort of epgscan loop by removing existing flag file !" 
			rm $FLG_FILE  > /dev/null 2>&1  					# remove flag file aborts a running epg scan
			exit
		fi
		start_log							# log epgscan started
		KEEP_LOG_ERROR=1
		msg "Fehler beim letzten Scan?" 
		log " "
		log "flag file exists: onother epgscan is still running or the last scan hang or aborted" 
		log "now I delete the flag file, this breaks the other epgscan loop if one is still running." 
		rm $FLG_FILE  > /dev/null 2>&1  					# remove flag file aborts a running epg scan
		sleep 60   #r damit das andere Script auch die Tasten absetzen konnte und fertig ist (30+7 sek)
		log " "
	else
		start_log							# log epgscan started
	fi

touch $FLG_FILE  > /dev/null 2>&1	

init_crontab					# initialize cron jobs in crontab

	if [ ! -e $FP_SCRIPT ]; then								# epgscan.sh missing
		log " " -t
		init_reelvdrd					# delete call of epgscan.sh in reelvdrd 
		rm $FLG_FILE  > /dev/null 2>&1	
		log "epgscan script finished without scan"
		exit 1
	fi

	init_reelvdrd					# initialize setting frontpanel timer for daily scan

COMMENT_TRY_LATER="# try later epgscan	author: broetlibahn"


# check if awoke by frontpanel timer
FP_WAKEUP=0
STB=0
SEEK="wakeup reason was:"
	if WAKE_SYSLOG_ENTRY=$(tac $SYSLOG_FILE | grep -m1 "$SEEK"); then
		WAKEUP=$(expr substr "$WAKE_SYSLOG_ENTRY" 1 15)
		WAKEUP_REASON=$(expr substr "$WAKE_SYSLOG_ENTRY" 54 55)
		WAKEUP_UTC=$(date -d "$(date -d "$WAKEUP" +%b" "%d" "%T)" +%s)
		log "last vdr wakeup in syslog: $(date -d @$WAKEUP_UTC +%y%m%d" "%T) reason=$WAKEUP_REASON" -d
		if inrange_utc $WAKEUP_UTC $BOOT1_S -s ; then			# wakeup was not less than allowed minutes
			if [ $WAKEUP_REASON = "05" ]||[ $WAKEUP_REASON = "01" ]; then			# wakeup by frontpanel timer / if tvtv plugin is installed reason cauld be 01
				log "wakeup from deep standby detected" -d
				FP_WAKEUP=1								# then we will have to shutdown again later
				$COMMAND HITK Power > /dev/null 2>&1
				if [ -e $STB_FILE ]; then 				# if fp wakeup went to standby 
					WAKE=1
					log "now I wakeup the vdr from standby mode" -d
					rm $STB_FILE  > /dev/null 2>&1
					sleep 30
				else
					# from Reelbox Firmware 9.12 December 2009 the wakeup by frontpanel timer the reelbox goes to quick standby 
					# therefore the first power key does wakeup from quick standby
					log "now I wakeup the vdr from QuickStandby" -d
					$COMMAND HITK Power > /dev/null 2>&1	# if wakeup went to quick standby: POWER
					$COMMAND HITK Back > /dev/null 2>&1		# if RB is not in quick standby, power key will shut down. Exit key breaks shut down
					sleep 1
				fi
				
			fi
		fi
	fi
	

	if [ -e $STB_FILE ]; then 
		STB=1
		log "standby mode detected" -d
	fi
	
# seek latest log entry where all channels were scanned succesfull to get the past hours since last scan
# searching for first matching record beginning from last record to first
SEEK="$CHANNELS OK"
LAST_OK_LOG_ENTRY=$(tac $LOG_FILE | grep -m1 "$SEEK")
PAST_H=1000
PAST_M=60000
LASTSCAN=0
LASTSCAN_UTC=0
WAIT_DAILY_M=0
WAKE=0
IS_DAILY_SCAN=0
FP_UTC=0
REC=0
		
	if [ -n "$LAST_OK_LOG_ENTRY" ]; then  				# match
		LASTSCAN=$(expr substr "$LAST_OK_LOG_ENTRY" 1 15)
		log "last complete scan $CHANNELS channels at $LASTSCAN" -d
		LASTSCAN_UTC=$(date -d "$LASTSCAN" +%s)			# last complete scan (utc)
		PAST_M=$((($(date +%s)-$LASTSCAN_UTC)/60))		# minutes past since last scan
		PAST_H=$(($PAST_M/60))							# hours past since last scan
		PAST_REM_M=$(($PAST_M%60))						# remaining minutes 
		if [ $PAST_REM_M -gt 0 ]; then
			WAIT_H=$(($WAIT_H-1))
			WAIT_REM_M=$((60-$PAST_REM_M))				# remaining minutes
		else
			WAIT_REM_M=0
		fi
	else
		# no match
		log "no last complete scan for $CHANNELS channels in log file" -d
		KEEP_LOG_ERROR=1		# logfile nicht löschen
	fi

# overwrite log file if new day and one entry was a complete succesfull scan.
# the last entry of succesfull scan will be saved as first entry
	if [ $KEEP_LOG -eq 0 ] && [ $KEEP_LOG_ERROR -eq 0 ]; then
		FIRSTENTRY=$(head -c 15 $LOG_FILE) 2>/dev/null
		FIRSTLOG=$(expr substr "$FIRSTENTRY" 1 6)
		TODAY=$(date +%y%m%d)
		if [ ! "$FIRSTLOG" = "$TODAY" ] && [ $LASTSCAN_UTC -gt 0 ] && [ -n "$LAST_OK_LOG_ENTRY" ]; then 
			rm $LOG_FILE  > /dev/null 2>&1
			log_header		# writes header in new logfile
			log "# overwriting logfile from $FIRSTLOG" -t
			log "$OLD_CRON_ENTRY" -t
			log "$LAST_OK_LOG_ENTRY" -t
			start_log							# log epgscan started
		fi
	fi

# check if it is a daily scan


# find out if this call of epgscan is a daily scan 
	if [ $DAILY_SCANS -gt 0 ] && [ $ABORT_SCAN -eq 0 ]; then
		# find out if it was a try again time of the front panel timer file
		if [ -s $FP_FILE ]; then
			FP_UTC=$(head -c 10 $FP_FILE)
			FP_STRING=$(cat $FP_FILE)		
			log "found epgscan.fp: $FP_STRING " -d
			if (inrange_utc $FP_UTC $BOOT1_S -s); then  # timer in range of - fp_timer difference from now, ignore future timers 
				IS_DAILY_SCAN=3
			elif [ $FP_UTC -lt $NOW_UTC ]; then
				log "remove old epgscan.fp" -d
				rm $FP_FILE  > /dev/null 2>&1			# remove old entry 
				if grep -q "$COMMENT_TRY_LATER" $CRON_FILE; then
					sed -i /"$COMMENT_TRY_LATER/d" $CRON_FILE 2>/dev/null  								# delete try later cron jobs
					log "delete old try later cron job" -d
				fi
			fi
		fi	
		
		# get the last nearest of the 2 daily_scan utc times and test if they were in time of BOOT_S to detect a daily scan
		YESTERDAY_UTC=$(($TODAY_UTC - 86400))			# if day changed need to test yesterday daily scans too
		if [ $IS_DAILY_SCAN -eq 0 ]; then
			LAST_DAILY_SCAN_UTC=$(( $TODAY_UTC + $DAILY1_S ))						# daily_scan1 today
			if (inrange_utc $LAST_DAILY_SCAN_UTC $BOOT1_S -s); then 
				IS_DAILY_SCAN=1														# today daily scan1 is in range to be a daily scan
			else 
				LAST_DAILY_SCAN_UTC=$(( $YESTERDAY_UTC + $DAILY1_S ))				# daily_scan1 yesterday 
				if (inrange_utc $LAST_DAILY_SCAN_UTC $BOOT1_S -s); then 
					IS_DAILY_SCAN=1													# yesterday daily scan1 is in range to be a daily scan
				elif [ $DAILY_SCANS -gt 1 ] && [ $DAILY1_HHMM -lt $DAILY2_HHMM ]; then		# 2 daily scans enabled, scan 1 must be lower than scan 2
				
					LAST_DAILY_SCAN_UTC=$(( $TODAY_UTC + $DAILY2_S ))				# daily_scan2 today
					if (inrange_utc $LAST_DAILY_SCAN_UTC $BOOT1_S -s); then 
						IS_DAILY_SCAN=2												# today daily scan2 is in range to be a daily scan
					else 
						LAST_DAILY_SCAN_UTC=$(( $YESTERDAY_UTC + $DAILY2_S ))		# daily_scan2 yesterday 
						if (inrange_utc $LAST_DAILY_SCAN_UTC $BOOT1_S -s); then 
							IS_DAILY_SCAN=2											# yesterday daily scan2 is in range to be a daily scan
						fi
					fi
				fi
			fi
		fi


		if [ $IS_DAILY_SCAN -gt 0 ]; then 
			log "daily scan detected" -d
			if grep -q "$COMMENT_TRY_LATER" $CRON_FILE; then
				sed -i /"$COMMENT_TRY_LATER/d" $CRON_FILE 2>/dev/null  								# delete try later cron jobs
				log "delete old try later cron job" -d
			fi
			
			# check if daily scan only wanted from standby and vdr is not in standby
			if [ $DAILY_SCAN_WAIT_M -gt 60 ]; then
				DAILY_SCAN_WAIT_M=60
				log "configuration error: DAILY_SCAN_WAIT > 60"
			elif [ $DAILY_SCAN_WAIT_M -lt 10 ]; then
				DAILY_SCAN_WAIT_M=10
				log "configuration error: DAILY_SCAN_WAIT < 10"
			fi
			
			if [ $PAST_M -lt $DAILY_SCAN_WAIT_M ]; then						# waiting time not past
				log "$DAILY_SCAN_WAIT_M minutes waiting not passed" -d
				log "last scan was just before $PAST_M minutes"
				msg "letzter Scan war vor $PAST_M m" 2
				log "epgscan script finished without scan"
				exit_shut_down
			fi
			
			if [ $DAILY_SCAN_ONLY_STB -gt 0 ] && [ $STB -eq 0 ] && [ $FP_WAKEUP -eq 0 ]; then # vdr active and only from standby allowed
				log "vdr is active, daily scan only from standby configured" 
				msg "Daily Scan, nur aus Standby konfiguriert" 2
				try_later								# try again at next full or half hour
				log "epgscan script finished without scan"
				rm $FLG_FILE  > /dev/null 2>&1			# remove flag file 
				exit 1
			fi
		fi
	fi


# exit when records are running

	if [ -e $REC_FILE ]; then REC=$(head -c 1 $REC_FILE); fi
	if [ $REC -gt 0 ]; then
		log "$REC active recording(s)"
		msg "$REC Aufnahme(n)" 2
#r		try_later		# try again at next full or half hour
#r		rm $FLG_FILE  > /dev/null 2>&1
#r		log "epgscan script finished without scan"
#r		exit 1
	fi

# cancel if not enough time for scan until next record
	# get date of next record from vdr (this works only when vdr not in standby)

	if [ $STB -eq 0 ]; then 
		# get time of next record from vdr 
		$COMMAND NEXT abs > $TEMP_FILE 2>/dev/null   # write answerstring into temporary file
		STRING=$(head -qn 2 $TEMP_FILE | tail -qn1 | cut -c 5-17)  	# read part of 2. line
		log "got next record timer string from vdr: $STRING" -d 
		NUMBER=$(echo $STRING | cut -f1 -d " ")     # 1. field ( may be used later ) I don't know what it is
		NEXTREC_UTC=$(echo $STRING | cut -f2 -d " " | cut -c 1-10)  # 2. field is utc date of next record timer, utc has a length of 10 digits
																	# if 1. field has  1 the last character of 2. field is \n 
		check_nextrec		# check if there is enough time for epgscan until nextrec_utc

	# get date of next record from from vdr wakeup file (this works only when vdr is in standby), wake up vdr from from standby

	elif  [ -e $WAKEUP_FILE ]; then	# this file contains the time of next wakeup for record in UTC 	 
		NEXT_WAKEUP_UTC=$(head -c 10 $WAKE_FILE)
		if date  -d @$NEXT_WAKEUP_UTC +%s > /dev/null 2>&1; then  # is valid utc date
			log "got next wakeup from vdr wakeup file: $NEXT_WAKEUP_UTC (utc) = $(date -d @$NEXT_WAKEUP_UTC +%y%m%d" "%R)" -d 
			NEXTREC_UTC=$(( $NEXT_WAKEUP_UTC + $BOOT_S ))				# add boot time for next record (wakeup = record - boot)

			check_nextrec		# check if there is enough time for epgscan until nextrec_utc
		fi
		# wake up from standby by deleting the vdr standby flag file
		WAKE=1
		log "now I wakeup the vdr from standby mode" -d
		rm $STB_FILE  > /dev/null 2>&1
		sleep 30
	fi


# ------------------ checks finished scan is allowed --------------------------


# -------------------   EPG-Scan  loop  -------------------------------------------------------

CH_COUNTER=0
LAST_SCANNED_CHANNEL=0

log "scan of $CHANNELS channels in $CHANNEL_GROUPS group(s) started"
msg "$CHANNELS Kanaele gestartet"

	channel_scan_loop 1 $GROUP1_FIRST_CHANNEL $GROUP1_LAST_CHANNEL
	if [ $? -eq 0 ]; then
		if [ $CHANNEL_GROUPS -gt 1 ]; then
			channel_scan_loop 2 $GROUP2_FIRST_CHANNEL $GROUP2_LAST_CHANNEL
			if [ $? -eq 0 ]; then
				if [ $CHANNEL_GROUPS -gt 2 ]; then
				channel_scan_loop 3 $GROUP3_FIRST_CHANNEL $GROUP3_LAST_CHANNEL
				fi
			fi
		fi
	fi


#------------------   scan finished ---------------------------------------------

	if [ $SCAN_MODE -eq 0 ]; then			# scanning in front
		# Back to Chan 1
		$COMMAND CHAN 1 > /dev/null 2>&1
		sleep 1
	fi
	
#r	if [ -e $FLG_FILE ]; then 
#r		rm $FLG_FILE
#r	fi

	if [ $CH_COUNTER -eq $CHANNELS ]; then
		# all channels scanned
		log "scan finished"
		log "$CH_COUNTER OK"
		if [ -s $FP_FILE ]; then
			log "deactivate old later try again by removing epgscan.fp" -d
			rm $FP_FILE  > /dev/null 2>&1			# remove old entry 
			if grep -q "$COMMENT_TRY_LATER" $CRON_FILE; then
				sed -i /"$COMMENT_TRY_LATER/d" $CRON_FILE 2>/dev/null  								# delete try later cron jobs
				log "delete old try later cron job" -d
			fi
		fi
		# actualization of search timers
		log "actualization of search timers" -d
		msg "Suchtimer werden aktualisiert" 
		$COMMAND PLUG epgsearch UPDS > /dev/null 2>&1 
		sleep 30
		msg "Scan fertig"
	else
		# not all channels scanned
		log "only $CH_COUNTER channels from $CHANNELS scanned"
		msg "nur $CH_COUNTER Kanaele von $CHANNELS gescannt"
	fi
	

exit_shut_down    # finish script, removes flagfile, if awoke shut down back to standby mode
