#!/bin/bash

cd /etc/vdr/vdrconvert

# Read environment
. ./vdrconvert.env

NewJobs=$1
JOBFIL=$2
LOGFILE=$3

[ "$DEBUG" = "yes" ] && set -x || LOGFILE=/dev/null

let LINES=0
LINES=`cat ${JOBFIL}|wc -l`
if [ $LINES -gt 0 ]
then
    cat ${JOBFIL}|head -n $LINES ${JOBFIL} | grep '^/' > ${NewJobs}
fi
[ "`cat $JOBFIL||head -n $LINES $JOBFIL|tail -1`" != "`tail -1 $JOBFIL`" ] && printf "%s " `tail -1 $JOBFIL` > $JOBFIL || < /dev/null > $JOBFIL
while [ `cat $NewJobs|wc -l` -gt 0 ]
do

	CMDLIN=`head -n1 $NewJobs`   # Job auslesen
      	let Number=1

	# Find Recording name
	DirNum=$(echo $CMDLIN|sed 's/\// /g'|wc -w)
	let DirNum=DirNum-1

	printf "{ print \$$DirNum }" >/tmp/awk.input-file.$$
	RecName=$(echo $CMDLIN|sed 's/\// /g'|awk -f /tmp/awk.input-file.$$)
	rm -f /tmp/awk.input-file.$$

	printf "\n\n\n---------------------------------------------------------------\n" >>$LOGFILE
	printf "\n\nStart of NoAD for $RecName\n\n" >>$LOGFILE

	
	RUNNING="`ps -A | grep -w 'noad' | wc -l`"

	if [ $RUNNING -gt 2 ] ; then
		echo "NoAD Scan is already running!" >>$LOGFILE
		echo "Sleeping for 1 Min." >>$LOGFILE
		sleep 60
		echo Insert Jobs in Queue again for later restart ... >>$LOGFILE
		cat $NewJobs >> $JOBFIL 
		exit 0
	fi

	/usr/local/bin/noad -v -v nice $CMDLIN >>$LOGFILE 2>&1

	date >>$LOGFILE
	printf "\n\nNoAD Finished for $RecName\n\n" >>$LOGFILE

	$SVDRPSEND MESG "NoAD Scan Finished for $RecName."

	# Next Job
	cp $NewJobs $NewJobs.$$
	grep -x -v "$CMDLIN" $NewJobs.$$ > $NewJobs
	rm $NewJobs.$$

done
