#!/bin/sh
# Version: 0.2.0 
# Author: Dimitrios Dimitrakos mail@dimitrios.de
# $Id: vdr2mp3.sh,v 1.15 2005/10/04 13:57:48 dimi Exp $

RM=rm
#RM=echo
vco_user=`id -n -u`
homedir=`cat /etc/passwd|grep "^${vco_user}:"|cut -f6 -d ':'`
. $homedir/.vdrconvert/vdrconvert.env
[ -r $homedir/.vdrconvert/vdr2mp3.env ] && . $homedir/.vdrconvert/vdr2mp3.env

PIDFILE="$VCORUNDIR/`basename ${0}.pid`"
echo "$$" >> $PIDFILE

trap do_clean SIGINT SIGQUIT SIGTERM 
do_clean() {
	if [ -f $PIDFILE ]
	then
	    TEMPPID=$LTEMPDIR/`basename $PIDFILE`.$$
	    mv $PIDFILE $TEMPPID
	    status=$?
	    if [ $status -eq 0 ]
	    then
	        [ `cat $TEMPPID|wc -l` -gt 0 ] && cat $TEMPPID|grep -v $$ > $PIDFILE 
	    fi
	    [ -f $TEMPPID ] && $RM $TEMPPID
	fi
	exit
}

Exit() {
	do_clean
}

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



[ "$MP3_DEBUG" = "yes" ] && set -x 

printf "`date +"%d-%m-%2Y %T"` : Session %s begin\n" "$0"

LTEMPDIR=${TEMPDIR}/${JOBFIL}
. $VDRCONVERTDIR/bin/helperfunctions.sh

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

# Default Options
[ -z "$MP3_DESTDIR" ]  && MP3_DESTDIR=$DESTDIR/mp3 
[ -z "$MP3_OPTS" ]     && MP3_OPTS="-b 192 -h --resample 44100"
[ -z "$MP3_SPLIT" ]    && MP3_SPLIT="no"
[ -z "$MPLAYERMP3SOURCE" ]    && MPLAYERMP3SOURCE=""
[ -z "$MP3_TITLEDATE" ] && MP3_TITLEDATE=$CONV_TITLEDATE
[ -z "$MP3_USE_MPG123" ] && MP3_USE_MPG123=no
[ -z "$MP3USESTREAMS" ] && MP3USESTREAMS="apid1 apid2"

[ -d $MP3_DESTDIR ] || mkdir -p $MP3_DESTDIR 
[ -d $LTEMPDIR ] || mkdir -p $LTEMPDIR

if [ -w ${LTEMPDIR} -a -w ${MP3_DESTDIR} ]
then
	let NLLINES=`cat $VCOQUEUEDIR/${JOBFIL}|nl|wc -l|awk '{ print $1 }'`
	let ALINES=`cat $VCOQUEUEDIR/${JOBFIL}|wc -l|awk '{ print $1 }'`

	if [ $ALINES -ge 1 ]
	then
		TEMPJOBFILE=/$LTEMPDIR/${JOBFIL}.u.$$
		> $TEMPJOBFILE
		printf "%s\n" "`cat $VCOQUEUEDIR/${JOBFIL}|head -n 1`" > $NewJobs
		let LINE=2
		while [ $LINE -le $ALINES ]
		do
			printf "%s\n" "`cat $VCOQUEUEDIR/${JOBFIL}|head -n $LINE|tail -n 1`" >> $TEMPJOBFILE
			let LINE=LINE+1
		done
		[ $NLLINES -gt $ALINES ] && printf "%s" "`cat $VCOQUEUEDIR/${JOBFIL}|tail -n 1`" >> $TEMPJOBFILE
		cp $TEMPJOBFILE $VCOQUEUEDIR/${JOBFIL} && $RM $TEMPJOBFILE


		while [ `cat $NewJobs|grep ^${VDRROOT}|wc -l` -gt 0 ]
		do
			CMDLIN=`head -n 1 $NewJobs`   # Job auslesen
			let Number=1
			printf "\t`date +"%T"` Start conversion for List : \n"
			let part=0
			for i in $CMDLIN
			do
				let part=part+1
				printf "\t\t %5d) %s\n" $part "$i"
			done
			for i in $CMDLIN
			do
			    [ "$MP3_SPLIT" = "no" ] && p=${i}/ || p=`echo $i/[0-9][0-9[0-9]*.vdr`
			    let part=1
			    for j in $p
			    do
				r=`echo $VDRROOT|sed 's/\// /g'|wc -w`
				spalten=`echo $j|sed 's/\// /g'|wc -w`
				[ "$MP3_SPLIT" = "no" ] || let spalten=spalten-1
				Record=`echo $j|sed 's/\%//g'|cut -f $spalten -d '/'`
				[ $[$r+2] -lt $[$spalten-1] ] && SubTitel=`echo $j|sed 's/\%//g'|cut -f $[$r+2]-$[$spalten-1] -d '/'` || SubTitel=""
				Datum=`basename $p|cut -f1 -d'.'`
				if [ -z "$SubTitel" ]
				then
					[ "$MP3_TITLEDATE" = "yes" ] && Titel=${Datum}_${Record} ||Titel=${Record}
				else
					[ "$MP3_TITLEDATE" = "yes" ] && Titel=${SubTitel}/${Datum}_${Record} || Titel=${SubTitel}/${Record}
				fi
				[ ! -d ${MP3_DESTDIR}/`dirname ${Titel}` ] && mkdir -p ${MP3_DESTDIR}/`dirname ${Titel}`

				printf "\n\t`date` : Begin conversion %s\n" "$Record"
				[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` start for $Record" > /dev/null 2>&1
				logger "`echo $0|xargs basename` start for $Record"

				UniqueDir[Number]=`mktemp -d ${LTEMPDIR}/VDRSYNC.XXXXXX`
				mkdir -p ${UniqueDir[Number]}/${Titel}
				cd ${UniqueDir[Number]}
				LOG[Number]=${UniqueDir[Number]}/sync.log
				for demux_prg in $DEMUXER
				do
					[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "Try demux with $demux_prg" > /dev/null 2>&1
               				printf "\t`date +"%T"`: Start demux with %s\n" ${demux_prg}
	       				pxfiles=""
               				case `basename $demux_prg` in
               					vdrsync)
                					nice -n $PRIO $VDRSYNC -audio-only -o ${UniqueDir[Number]} $j > ${LOG[Number]} 2>&1
                					status=$?
                					if [ $status -ne 0 ]
                					then
                  						echo "ERROR : $VDRSYNC  rc=$status"
	          						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "ERROR : $VDRSYNC  rc=$status" > /dev/null 2>&1
		  						logger "ERROR : $VDRSYNC  rc=$status"
                  						# Cleaning
                  						cd $VDRCONVERTDIR
                  						$RM -rf ${UniqueDir[Number]}
                  						Exit
                					fi
                					;;
						vdrsync2)
							nice -n $PRIO $VDRSYNC2 -audio-only -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $j > ${LOG[Number]} 2>&1
							status=$?
							if [ $status -ne 0 ]
							then
								echo "ERROR : $VDRSYNC2  rc=$status"
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "ERROR : $VDRSYNC2  rc=$status" > /dev/null 2>&1
								logger "ERROR : $VDRSYNC2  rc=$status"
								# Cleaning
								cd $VDRCONVERTDIR
								$RM -rf ${UniqueDir[Number]}
								Exit
							fi
							;;
						vdrsync3)
							nice -n $PRIO $VDRSYNC3 -audio-only -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $j > ${LOG[Number]} 2>&1
							status=$?
							if [ $status -ne 0 ]
							then
								echo "ERROR : $VDRSYNC3  rc=$status"
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "ERROR : $VDRSYNC3  rc=$status" > /dev/null 2>&1
								logger "ERROR : $VDRSYNC3  rc=$status"
								# Cleaning
								cd $VDRCONVERTDIR
								$RM -rf ${UniqueDir[Number]}
								Exit
							fi
							;;
						px)
							# Virtuellen X-Server starten
							#$XVFB :1 >/dev/null 2>&1 &
							#export DISPLAY=:1.0
	
							[ -d $j ] && vdrfiles=$j/[0-9][0-9][0-9].vdr || vdrfiles=$j
              						for l in $vdrfiles
              						do
		  						# fix -n 001 problem
                  						let len=`$LS -Ls $l|awk '{print $1}'`
                  						if [ $len -gt 1 ]
                  						then
                      						    if [ -z "$pxfiles" -a "`echo $l|xargs basename`" != "001.vdr" ]
                      						    then
										ln -s $l ${UniqueDir[Number]}/001.vdr
										l=${UniqueDir[Number]}/001.vdr
                      						    fi
                      						    pxfiles="${pxfiles} ${l}"
                  						fi
              						done
	
							# Project X starten
							echo "Verarbeitung fuer pxfiles = $pxfiles" > ${LOG[Number]} 2>&1
							nice -n $PRIO $JAVA -jar $PX $PXINIOPT $PXINI $PXOUTOPT ${UniqueDir[Number]} $pxfiles >> ${LOG[Number]} 2>&1
							status=$?
	
							let z=0
							for i in `cat ${LOG[Number]}|grep "found PES-ID 0xC"|awk '{print $4}'`
							do
			    					let z=z+1
			    					str=`cat ${LOG[Number]}|tr -d "\r"|grep ^Audio|grep -v "PTS"|grep "(mp2)"|awk '{print $8}'|head -n $z|tail -n 1|xargs basename`
			    					strn=`echo $i|cut -f2 -d 'x'|awk '{ print tolower($1)'}`
			    					mv ${UniqueDir[Number]}/${str}  ${UniqueDir[Number]}/${strn}.mpa
							done
							# Virtuellen X-Server beenden
							#$KILL -15 $XVFB >/dev/null
							if [ $status -ne 0 ]
							then
								echo "ERROR : $PX  rc=$status"
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "ERROR : $PX  rc=$status" > /dev/null 2>&1
								logger "ERROR : $PX  rc=$status"
								# Cleaning
								cd $VDRCONVERTDIR
								$RM -rf ${UniqueDir[Number]}
								Exit
							fi
							;;
						pva)
							# VDR Files zusammenfuehren
							[ -d $j ] && pvafiles=$j/[0-9][0-9][0-9].vdr || pvafiles=$j
							[ -f ${UniqueDir[Number]}/001.vdr ] && $RM ${UniqueDir[Number]}/001.vdr
							cat $pvafiles >> ${UniqueDir[Number]}/001.vdr
							#cat $i/[0-9][0-9][0-9].vdr >> ${UniqueDir[Number]}/001.vdr
							[ -f $i/marks.vdr ] && cp $i/marks.vdr ${UniqueDir[Number]}
							[ -f $i/index.vdr ] && cp $i/index.vdr ${UniqueDir[Number]}
							# Winpfad erstellen
							WINEPFAD=`echo ${UniqueDir[Number]}|sed 's/\//\\\/g'`
							WINEFILE="demux \"Z:${WINEPFAD}\\001.vdr\" \"Z:${WINEPFAD}\\001.mpv\" \"Z:${WINEPFAD}\\001.mpa\""
							## Jobfile anlegen
							echo "offeryn pvas job v000001" > ${UniqueDir[Number]}/demux.ajb
							echo "\$JOB" >> ${UniqueDir[Number]}/demux.ajb
							echo "$WINEFILE" >> ${UniqueDir[Number]}/demux.ajb
							cat $VDRCONVERTDIR/share/vdrconvert/pva/demux.template >> ${UniqueDir[Number]}/demux.ajb
	
							#$XVFB :1 >/dev/null 2>&1 &
							#export DISPLAY=:1.0
	
							nice -n $PRIO $WINE $VDRCONVERTDIR/share/vdrconvert/pva/cPVAS.exe ${UniqueDir[Number]}/demux.ajb > ${LOG[Number]} 2>&1
							status=$?
							$RM -rf ${UniqueDir[Number]}/001.vdr
							#[ -f "${UniqueDir[Number]}/001.mpv.ac3" ] && mv ${UniqueDir[Number]}/001.mpv.ac3 ${UniqueDir[Number]}/001.ac3
							#$KILL -15 $XVFB >/dev/null
							;;
						*)
							printf "\t\tNo support for Demuxer %s\n" $dumux_prg
							logger "No support for Demuxer $dumux_prg"
							;;
					esac
					# Check audio
					let NAudio=0
					if [ $status -eq 0 ]
					then
						NAudio=`$LS -l ${UniqueDir[Number]}/*.mpa 2>/dev/null|wc -l|awk '{print $1}'`
						[ $NAudio -eq 0 ] && status=1
					fi
					if [ $status -eq 0 ]
					then
						TDEMUXER[Number]=$demux_prg
						break
					fi
				done
				NEWSTREAMS=""
				if [ ! -z ${TDEMUXER[Number]} ]
				then
				    USESTREAMS=$(find_streams ${TDEMUXER[Number]} ${UniqueDir[Number]} $MP3USESTREAMS)
				    spart=`printf "%03d" $part`
                                    echo "s/001/$spart/g" > /tmp/sedcmd.$$
                                    STREAMS=`echo $USESTREAMS|sed -f /tmp/sedcmd.$$`
                                    [ -f /tmp/sedcmd.$$ ] && $RM /tmp/sedcmd.$$
				    for ii in ${STREAMS}
				    do
				         [ -r ${UniqueDir[Number]}/${ii} ] \
					    && NEWSTREAMS="$NEWSTREAMS ${ii}"
				    done
				fi
	
				if [ ! -z "$NEWSTREAMS" ]
				then
				    for AUDIO in $NEWSTREAMS
				    do
					if [ -f ${UniqueDir[Number]}/$AUDIO -a "`echo $AUDIO|xargs basename|cut -f2 -d'.'`" != "ac3" ]
					then
					    # Mit Lame zu mp3
					    if [ "$MP3_USE_MPG123" != "yes" ]
					    then
						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "start LAME for ${Titel}.mp3" > /dev/null 2>&1
						printf "\t`date +"%T"`: Start LAME for %s in %s with $MP3_OPTS\n" "${AUDIO}" "${Titel}"
						nice -n ${PRIO} $LAME --mp2input $MP3_OPTS ${UniqueDir[Number]}/$AUDIO ${UniqueDir[Number]}/${Titel}.mp3 > /dev/null 2>&1
					    else
						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "start mpg123|lame for ${Titel}.mp3" > /dev/null 2>&1
						printf "\t`date +"%T"`: Start mpg123 | LAME for %s in %s with $MP3_OPTS\n" "${AUDIO}" "${Titel}"
						nice -n $PRIO mpg123 -s -w - ${UniqueDir[Number]}/$AUDIO | $LAME $MP3_OPTS - ${UniqueDir[Number]}/${Titel}.mp3 > /dev/null 2>&1
						[ -f out.$$.wav ] && $RM -f out.$$.wav
					    fi
					    if [ -f ${UniqueDir[Number]}/${Titel}.mp3 ]
					    then
						if [ ! -f ${MP3_DESTDIR}/${Titel}.mp3 ]
						then
							cp ${UniqueDir[Number]}/${Titel}.mp3 ${MP3_DESTDIR}/${Titel}.mp3
							File=${MP3_DESTDIR}/${Titel}.mp3
						else
							let index=1
							until [ ! -f ${MP3_DESTDIR}/${Titel}-$index.mp3 ]
							do
								let index=index+1
							done
							cp ${UniqueDir[Number]}/${Titel}.mp3 ${MP3_DESTDIR}/${Titel}-$index.mp3
							File=${MP3_DESTDIR}/${Titel}-$index.mp3
						fi
						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "MP3 for $File success" > /dev/null 2>&1
						printf "\t`date +"%T"`: MP3 for %s success\n" "$File"
						logger "$0 : MP3 for $File success"
					    else
						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "MP3 for $File fail" > /dev/null 2>&1
						printf "\t`date +"%T"`: MP3 for %s fail\n" "$File"
						logger "$0 : AC3 for $File fail"
					    fi
					fi
				    done
				fi
			    	cd -
			    	$RM -rf ${UniqueDir[Number]}
			    	let Number=Number+1
			    	let part=part+1
			    done
			    #cd -
			    #$RM -rf ${UniqueDir[Number]}
			    #let Number=Number+1
			    printf "\t`date` : Finish %s\n" "$i"
			    cp $NewJobs $NewJobs.$$
			    grep -x -v "$CMDLIN" $NewJobs.$$ > $NewJobs 
			    $RM $NewJobs.$$
			done
		done
		# Cleaning
		printf "\t`date +"%T"` Parts from List : \n"
		let part=0
		for i in $CMDLIN
		do
			let part=part+1
			printf "\t\t %5d) %s\n" $part "$i"
		done
		printf "\t`date +"%T"` completed\n"
		$RM $NewJobs
	fi
else
		echo "ERROR : ${MP3_DESTDIR} or ${LTEMPDIR} are not writable. $0 exit"
fi
printf "`date +"%d-%m-%2Y %T"` : Session %s end\n" "$0"
Exit
