#!/bin/sh
# Version: 0.2.0
# Author: Dimitrios Dimitrakos mail@dimitrios.de
# $Id: vdr2mpg.sh,v 1.14 2005/10/04 13:57:56 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/vdr2mpg.env ] && . $homedir/.vdrconvert/vdr2mpg.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



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

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

[ -z "$MPG_DESTDIR" ]   && MPG_DESTDIR=$DESTDIR/mpg 
[ -z "$MPG_TITLEDATE" ] && MPG_TITLEDATE=$CONV_TITLEDATE
[ -z "$MPGUSESTREAMS" ] && MPGUSESTREAMS="dpid1 apid1 apid2"

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

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

if [ -w ${LTEMPDIR} -a -w ${MPG_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
	  [ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` start for $i" > /dev/null 2>&1
	  logger "`echo $0|xargs basename` start for $i"
	  pxfiles=""
          printf "\n\t`date` : Begin conversion %s\n" "$i"
	  UniqueDir[Number]=`mktemp -d ${LTEMPDIR}/VDRSYNC.XXXXXX`
	  r=`echo $VDRROOT|sed 's/\// /g'|wc -w`
	  spalten=`echo $i|sed 's/\// /g'|wc -w`
	  Record=`echo $i|sed 's/\%//g'|cut -f $spalten -d '/'`
	  [ $[$r+2] -lt $[$spalten-1] ] && SubTitel=`echo $i|sed 's/\%//g'|cut -f $[$r+2]-$[$spalten-1] -d '/'` || SubTitel=""
	  Datum=`basename $i|cut -f1 -d'.'`
	  if [ -z "$SubTitel" ]
	  then
		[ "$MPG_TITLEDATE" = "yes" ] && Titel=${Datum}_${Record} ||Titel=${Record}
	  else
		[ "$MPG_TITLEDATE" = "yes" ] && Titel=${SubTitel}/${Datum}_${Record} || Titel=${SubTitel}/${Record}
	  fi
	  [ ! -d ${UniqueDir[Number]}/${SubTitel} ] && mkdir -p ${UniqueDir[Number]}/${SubTitel}
	  [ ! -d ${MPG_DESTDIR}/${SubTitel} ] && mkdir -p ${MPG_DESTDIR}/${SubTitel}
	  mkdir -p ${UniqueDir[Number]}
	  LOG[Number]=${UniqueDir[Number]}/sync.log
	  for demux_prg in $DEMUXER
	  do
	    [ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "Try demux with $DEMUXER" > /dev/null 2>&1
            printf "\t`date +"%T"`: Start demux with %s\n" ${DEMUXER}
            case `basename $DEMUXER` in
            vdrsync)
              nice -n $PRIO $VDRSYNC -o ${UniqueDir[Number]} $i/ > ${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 "$0 : ERROR : $VDRSYNC  rc=$status"
                  # Cleaning
                  cd $VDRCONVERTDIR
                  $RM -rf ${UniqueDir[Number]}
                  Exit
              fi
              ;;
            vdrsync2)
              nice -n $PRIO $VDRSYNC2 -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $i/ > ${LOG[Number]} 2>&1
              status=$?
              if [ $status -ne 0 ]
              then
                  echo "ERROR : $VDRSYNC2  rc=$status"
		  logger "$0 : ERROR : $VDRSYNC2  rc=$status"
                  # Cleaning
                  cd $VDRCONVERTDIR
                  $RM -rf ${UniqueDir[Number]}
                  Exit
              fi
              ;;
            vdrsync3)
              nice -n $PRIO $VDRSYNC3 -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $i/ > ${LOG[Number]} 2>&1
              status=$?
              if [ $status -ne 0 ]
              then
                  echo "ERROR : $VDRSYNC3  rc=$status"
		  logger "$0 : 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

              vdrfiles=`$LS $i/[0-9][0-9][0-9].vdr`
              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
              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"
		  logger "$0 : ERROR : $PX  rc=$status"
                  # Cleaning
                  cd $VDRCONVERTDIR
                  $RM -rf ${UniqueDir[Number]}
                  Exit
              fi
              ;;
            pva)
              # VDR Files zusammenfuehren
              cat $i/[0-9][0-9][0-9].vdr >> ${UniqueDir[Number]}/001.vdr
              # 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=$?
              [ -f "${UniqueDir[Number]}/001.mpv.ac3" ] && mv ${UniqueDir[Number]}/001.mpv.ac3 ${UniqueDir[Number]}/001.ac3

              #$KILL -15 $XVFB >/dev/null
              ;;
            *)
              echo "No support for Demuxer $DEMUXER"
              ;;
            esac
	    [ "$DEBUG" = "yes" ] && cat ${LOG[Number]}
	    # 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
	  [ $NAudio -eq 0 ] && Exit
	  USESTREAMS=$(find_streams ${TDEMUXER[Number]} ${UniqueDir[Number]} $MPGUSESTREAMS)
	  NEWSTREAMS[Number]=$USESTREAMS

	  AC3="no"
	  for i in ${NEWSTREAMS[Number]}
	  do
	     [ -f ${UniqueDir[Number]}/$i -a "`echo $i|xargs basename|cut -f2 -d'.'`" = "ac3" ] && AC3="$i"
	  done
	  echo "s/$AC3//g" > /tmp/mpgsed.$$
	  [ "$AC3" != "no" ] && NEWSTREAMS[Number]=`echo ${NEWSTREAMS[Number]}|sed -f /tmp/mpgsed.$$`
	  [ -f /tmp/mpgsed.$$ ] && rm /tmp/mpgsed.$$

          VIDEO=${UniqueDir[Number]}/*.mpv
	  if [ -f $VIDEO ]
	  then
	    for AUDIO in ${NEWSTREAMS[Number]}
	    do
	      if [ -f ${UniqueDir[Number]}/$AUDIO ]
	      then
	        if [ "$AC3" != "no" ]
	        then 
                  printf "\t`date +"%T"`: Start TCMPLEX for %s. AC3 in %s, Mpeg in %s\n" "${Titel}" "$AC3" "$AUDIO" 
	          nice -n ${PRIO} $TCMPLEX -i $VIDEO -p ${UniqueDir[Number]}/$AC3 -s ${UniqueDir[Number]}/$AUDIO -m d -o ${UniqueDir[Number]}/${Titel}.mpg >/dev/null 2>&1
	        else
                  printf "\t`date +"%T"`: Start TCMPLEX for %s.  Mpeg in %s\n" "${Titel}" "$AUDIO"
	          nice -n ${PRIO} $TCMPLEX -i $VIDEO -p ${UniqueDir[Number]}/$AUDIO -m d -o ${UniqueDir[Number]}/${Titel}.mpg>/dev/null 2>&1
	        fi
	        if [ -f ${UniqueDir[Number]}/${Titel}.mpg ]
	        then
	          if [ ! -f ${MPG_DESTDIR}/${Titel}.mpg ]
	          then
	              mv ${UniqueDir[Number]}/${Titel}.mpg ${MPG_DESTDIR}/${Titel}.mpg
	              status=$?
	              File=${MPG_DESTDIR}/${Titel}.mpg
	          else
	              let index=1
	              until [ ! -f ${MPG_DESTDIR}/${Titel}-${index}.mpg ]
	              do
	                  let index=index+1
	              done
	              mv ${UniqueDir[Number]}/${Titel}.mpg ${MPG_DESTDIR}/${Titel}-${index}.mpg
	              status=$?
	              File=${MPG_DESTDIR}/${Titel}-${index}.mpg
	          fi
	          if [ $status -eq 0 ]
		  then
		 	$SVDRPSEND MESG "MPG for ${Titel}.mpg success" > /dev/null 2>&1
                        printf "\t`date +"%T"`: MPG for %s success\n" "$File"
		  else
		  	$SVDRPSEND MESG "MPG for ${Titel}.mpg fail" > /dev/null 2>&1
                        printf "\t`date +"%T"`: MPG for %s fail\n" "$File"
		  fi
	        else
		 [ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "ERROR : TCMPLEX for MPG ${Titel}.mpg" > /dev/null 2>&1
                 printf "\t`date +"%T"`: TCMPLEX for %s fail\n" "$Titel"
	        fi

	        if [ "$MPG_AUTOWRITE" = "yes" ]
                then
		    echo "${File}:CD:DEL" >> $VCOQUEUEDIR/burn
	        fi
	      fi
	    done
	  fi
          $RM -rf ${UniqueDir[Number]}
	  let Number=Number+1
          printf "\t`date` : Finish %s\n" "$i"
      done
      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"
      cp $NewJobs $NewJobs.$$
      grep -x -v "$CMDLIN" $NewJobs.$$ > $NewJobs 
      $RM $NewJobs.$$
    done
    $RM $NewJobs
  fi
else
      echo "ERROR : ${MPG_DESTDIR} or ${LTEMPDIR} are not writable. $0 exit"
fi
printf "`date +"%d-%m-%2Y %T"` : Session %s end\n" "$0"
Exit
