#!/bin/sh
# Version: 0.2.0
# Author: Dimitrios Dimitrakos mail@dimitrios.de
# $Id: burn.sh,v 1.5 2005/04/08 11:38:45 dimi Exp $

# Read environment
vco_user=`id -n -u`
homedir=`cat /etc/passwd|grep "^${vco_user}:"|cut -f6 -d ':'`
. $homedir/.vdrconvert/vdrconvert.env
[ -r $homedir/.vdrconvert/burn.env ] && . $homedir/.vdrconvert/burn.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

LTEMPDIR=${TEMPDIR}/${JOBFIL}
[ -d $LTEMPDIR ] || mkdir -p $LTEMPDIR

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

echo "`date +"%d-%m-%2Y %T"` : Session $0 begin" 
echo "" 

# Default values
[ -z "$BURN_DESTDIR" ]  && BURN_DESTDIR=$DESTDIR/burn
# Devices
[ -z "$MEDIAWRITER" ]          && MEDIAWRITER="/dev/scd0:0,0,0"
WRITER=`echo $MEDIAWRITER|cut -f 1 -d ':'`
WRITER_DEV=`echo $MEDIAWRITER|cut -f 2 -d ':'`
WRITER_ADR=`echo $MEDIAWRITER|cut -f 3 -d ':'`
# Options
[ -z "$DVDPLUS_RECORD_OPTS" ]  && DVDPLUS_RECORD_OPTS="-Z"
[ -z "$DVDMIN_RECORD_OPTS" ]   && DVDMIN_RECORD_OPTS="-dao driveropts=burnfree"
[ -z "$DVD_RECORDCMD" ]        && DVD_RECORDCMD="growisofs"
[ -z "$DVDMIN_RECORDCMD" ]     && DVDMIN_RECORDCMD="dvdrecord"
[ -z "$DAO_RECORDCMD" ]        && DAO_RECORDCMD="cdrdao"
[ -z "$CD_RECORDCMD" ]         && CD_RECORDCMD="cdrecord"
[ -z "$MEDIA_RW_FORMAT" ]      && MEDIA_RW_FORMAT="yes"
[ -z "$DVDPLUS_BLANK_CMD" ]    && DVDPLUS_BLANK_CMD="dvd+rw-format -f"
[ -z "$DVDMIN_BLANK_CMD" ]     && DVDMIN_BLANK_CMD="dvdrecord -dao blank=fast"
[ -z "$DVDSTATUSPRG" ]	       && DVDSTATUSPRG="dvd+rw-mediainfo"
[ -z "$DAO_OPTS" ]             && DAO_OPTS="--driver generic-mmc --overburn"
[ -z "$CD_OPTS" ]              && CD_OPTS="driveropts=dao gracetime=0"
[ -z "$BURN_MAXRETRY" ]        && BURN_MAXRETRY=3
[ -z "$BURN_DISABLE_EJECT" ]   && BURN_DISABLE_EJECT="no"
# DVD-SVDRPSEND MESSAGES
case $VDRCONVERT_LANG in
	de|DE )
		[ -z "$MEDIA_MSG_OK" ]                 && MEDIA_MSG_OK="Medium wurde erfolgreich erstellt"
		[ -z "$MEDIA_MSG_ERROR" ]              && MEDIA_MSG_ERROR="Fehler beim Schreibvorgang"
		[ -z "$MEDIA_MSG_INSERT_CD" ]          && MEDIA_MSG_INSERT_CD="Bitte legen sie ein CD Medium ein"
		[ -z "$MEDIA_MSG_INSERT_DVD" ]         && MEDIA_MSG_INSERT_DVD="Bitte legen sie ein DVD Medium ein"
		[ -z "$MEDIA_MSG_START_FORMAT" ]       && MEDIA_MSG_START_FORMAT="Medium wird geloescht"
		[ -z "$MEDIA_MSG_ISO_READYTOBURN" ]    && MEDIA_MSG_ISO_READYTOBURN="Isodatei ist fertig zum Brennen"
		[ -z "$MEDIA_MSG_START_WRITE_IMAGE" ]  && MEDIA_MSG_START_WRITE_IMAGE="Imagedatei wird gebrannt"
		[ -z "$MEDIA_MSG_RETRY_IN_X_MINUTES" ] && MEDIA_MSG_RETRY_IN_X_MINUTES="Wiederholung in 5 Minuten"
		;;
	*)
		[ -z "$MEDIA_MSG_OK" ]                 && MEDIA_MSG_OK="Media was successfully detected"
		[ -z "$MEDIA_MSG_ERROR" ]              && MEDIA_MSG_ERROR="Failure to write"
		[ -z "$MEDIA_MSG_INSERT_CD" ]          && MEDIA_MSG_INSERT_CD="Please insert CD"
		[ -z "$MEDIA_MSG_INSERT_DVD" ]         && MEDIA_MSG_INSERT_DVD="Please insert DVD"
		[ -z "$MEDIA_MSG_START_FORMAT" ]       && MEDIA_MSG_START_FORMAT="Beginning to format medium"
		[ -z "$MEDIA_MSG_ISO_READYTOBURN" ]    && MEDIA_MSG_ISO_READYTOBURN="ISO ready to burn"
		[ -z "$MEDIA_MSG_START_WRITE_IMAGE" ]  && MEDIA_MSG_START_WRITE_IMAGE="Starting to write image"
		[ -z "$MEDIA_MSG_RETRY_IN_X_MINUTES" ] && MEDIA_MSG_RETRY_IN_X_MINUTES="Retry in 5 minutes"
		;;
esac	

[ -d $BURN_DESTDIR ] || mkdir -p $BURN_DESTDIR 
[ -d $TEMPDIR ] || mkdir -p $TEMPDIR

if [ -w ${TEMPDIR} -a -w ${BURN_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|wc -l` -gt 0 ]
    do
      CMDLIN=`head -n 1 $NewJobs`   # Job auslesen
      DATA=`echo $CMDLIN|cut -f1 -d ':'`
      SYSTEM=`echo $CMDLIN|cut -f2 -d ':'`
      POSTACTION=`echo $CMDLIN|cut -f3 -d ':'`
      if [ ! -r $DATA ]
      then
	echo "ERROR : $DATA can not be read"
	Exit
      fi
      echo "`date` : Start burning session for $CMDLIN"
      UniqueBURNDIR=`mktemp -d ${TEMPDIR}/BURN.XXXXXX` 
      status=$?
      if [ $status -ne 0 ]
      then
	echo "ERROR : unable to create UniqueBURNDIR"
        Exit
      fi
      mkdir -p ${UniqueBURNDIR}

      case $SYSTEM in
	DVD|DVDDATA)
                let status=1
                let round=0
                let copy=1
                until [ $status -eq 0 -o $round -ge $BURN_MAXRETRY ]
                do
                     $SVDRPSEND MESG $MEDIA_MSG_INSERT_DVD >> /dev/null 2>&1
                     [ "$BURN_DISABLE_EJECT" != "yes" ] && eject $WRITER 2>/dev/null
                     sleep 30
                     [ "$BURN_DISABLE_EJECT" != "yes" ] && eject -t $WRITER 2>/dev/null
		     sleep 10
                     DVDTYPE=`$DVDSTATUSPRG $WRITER|grep "Mounted Media:"|awk '{print $4}'`
                     [ "$DVD_USE_ONLY_PLUS_CMDS" = "yes" -a "$DVDTYPE" = "DVD-RW" ] && DVDTYPE="DVD+RW"
                     [ "$DVD_USE_ONLY_PLUS_CMDS" = "yes" -a "$DVDTYPE" = "DVD-R" ] && DVDTYPE="DVD+R"
                     if [ "$MEDIA_RW_FORMAT" = "yes" ]
	             then
                         dvdstatus=`$DVDSTATUSPRG $WRITER|grep status|awk '{print $3}'`
                         if [ "$dvdstatus" != "blank" ]
                         then
                             $SVDRPSEND MESG $MEDIA_MSG_START_FORMAT >> /dev/null 2>&1
	                     case $DVDTYPE in
		                   "DVD-RW")
                                           $DVDMIN_BLANK_CMD dev=$WRITER_ADR
			                   ;;
		                   "DVD+RW")
                                           $DVDPLUS_BLANK_CMD $WRITER
                       		           sleep 10
                       		           if [ ! -z "$DVD_BOOKTYPE_CMD" ]
                       		           then
                           		           $DVD_BOOKTYPE_CMD
                           		           sleep 10
                       		           fi
			                   ;;
				      *)
				           ;;
	                     esac
                         fi
                     fi
                     $SVDRPSEND MESG $MEDIA_MSG_START_WRITE_IMAGE >> /dev/null 2>&1
	             case $DVDTYPE in
		            "DVD-RW"|"DVD-R")
          		            $DVDMIN_RECORDCMD $DVDMIN_RECORD_OPTS dev=$WRITER_DEV:$WRITER_ADR $DATA
			            ;;
		            *)
          		            $DVD_RECORDCMD $DVDPLUS_RECORD_OPTS "$WRITER=$DATA"
			            ;;
	             esac
            
                     status=$?
                     if [ $status -eq 0 ]
                     then
                          $SVDRPSEND MESG $MEDIA_MSG_OK >> /dev/null 2>&1
                          [ "$POSTACTION" = "DEL" ] && rm -rf $DATA
                          [ "$BURN_DISABLE_EJECT" != "yes" ] && eject $WRITER 2>/dev/null
			  sleep 120
                          [ "$BURN_DISABLE_EJECT" != "yes" ] && eject -t $WRITER 2>/dev/null
			  sleep 10
                     else
                          $SVDRPSEND MESG $MEDIA_MSG_ERROR >> /dev/null 2>&1
                          sleep 5
                          let round=round+1
                          if [ $round -lt $BURN_MAXRETRY ]
	                  then
		            $SVDRPSEND MESG $MEDIA_MSG_RETRY_IN_X_MINUTES >> /dev/null 2>&1
                            sleep 300
	                  fi
                     fi
                 done
	         ;;
	MINIDVD|CDIMAGE)
                let status=1
                let round=0
                let copy=1
                until [ $status -eq 0 -o $round -ge $BURN_MAXRETRY ]
                do
                     $SVDRPSEND MESG $MEDIA_MSG_INSERT_CD >> /dev/null 2>&1
                     [ "$BURN_DISABLE_EJECT" != "yes" ] && eject $WRITER 2>/dev/null
                     sleep 60
                     [ "$BURN_DISABLE_EJECT" != "yes" ] && eject -t $WRITER 2>/dev/null
		     sleep 10

                     if [ "$MEDIA_RW_FORMAT" = "yes" ]
	             then

                         cdrwstatus=`$DAO_RECORDCMD disk-info $DAO_OPTS --device $WRITER_ADR 2>/dev/null|grep CD-RW|tail -n 1|awk '{print $3}'`
                         if [ "$cdrwstatus" = "yes" ]
                         then
                             cdemptystatus=`$DAO_RECORDCMD disk-info $DAO_OPTS --device $WRITER_ADR 2>/dev/null|grep empty|tail -n 1|awk '{print $4}'`
                             if [ "$cdemptystatus" != "yes" ]
			     then
                                 $SVDRPSEND MESG $CD_MSG_START_FORMAT >> /dev/null 2>&1
			         $DAO_RECORDCMD blank $DAO_OPTS --device $WRITER_ADR
                             fi
                         fi
                     fi
                     $SVDRPSEND MESG $MEDIAD_MSG_START_WRITE_IMAGE >> /dev/null 2>&1
		     $CD_RECORDCMD $CD_OPTS dev=$WRITER_ADR $DATA
            
                     status=$?
                     if [ $status -eq 0 ]
                     then
                          $SVDRPSEND MESG $MEDIA_MSG_OK >> /dev/null 2>&1
                          [ "$POSTACTION" = "DEL" ] && rm -rf $DATA
                          [ "$BURN_DISABLE_EJECT" != "yes" ] && eject $WRITER 2>/dev/null
			  sleep 120
                          [ "$BURN_DISABLE_EJECT" != "yes" ] && eject -t $WRITER 2>/dev/null
			  sleep 10
                     else
                          $SVDRPSEND MESG $MEDIA_MSG_ERROR >> /dev/null 2>&1
                          sleep 5
                          let round=round+1
                          if [ $round -lt $BURN_MAXRETRY ]
	                  then
		            $SVDRPSEND MESG $MEDIA_MSG_RETRY_IN_X_MINUTES >> /dev/null 2>&1
                            sleep 300
	                  fi
                     fi
                 done
	         ;;
	CUE|CD)
                let status=1
                let round=0
                let copy=1
                until [ $status -eq 0 -o $round -ge $BURN_MAXRETRY ]
                do
                     $SVDRPSEND MESG $MEDIA_MSG_INSERT_CD >> /dev/null 2>&1
                     [ "$BURN_DISABLE_EJECT" != "yes" ] && eject $WRITER 2>/dev/null
                     sleep 60
                     [ "$BURN_DISABLE_EJECT" != "yes" ] && eject -t $WRITER 2>/dev/null
		     sleep 10

                     if [ "$MEDIA_RW_FORMAT" = "yes" ]
	             then

                         cdrwstatus=`$DAO_RECORDCMD disk-info $DAO_OPTS --device $WRITER_ADR 2>/dev/null|grep CD-RW|tail -n 1|awk '{print $3}'`
                         if [ "$cdrwstatus" = "yes" ]
                         then
                             cdemptystatus=`$DAO_RECORDCMD disk-info $DAO_OPTS --device $WRITER_ADR 2>/dev/null|grep empty|tail -n 1|awk '{print $4}'`
                             if [ "$cdemptystatus" != "yes" ]
			     then
                                 $SVDRPSEND MESG $CD_MSG_START_FORMAT >> /dev/null 2>&1
			         $DAO_RECORDCMD blank $DAO_OPTS --device $WRITER_ADR
                             fi
                         fi
                     fi

                     $SVDRPSEND MESG $MEDIA_MSG_START_WRITE_IMAGE >> /dev/null 2>&1

	     case $SYSTEM in
			CD)
				cd `dirname $DATA`
				status=$?
				if [ $status -eq 0 ]
				then
				    $MKISOFS -R -o ${UniqueBURNDIR}/image.iso `basename $DATA`
				    status=$?
				    cd -
				    if [ $status -eq 0 ]
				    then
				        $CD_RECORDCMD $CD_OPTS dev=$WRITER_ADR ${UniqueBURNDIR}/image.iso
				        status=$?
				        if [ ! $status -eq 0 ]
				        then
				            echo "Error : rc=$status $CD_RECORDCMD"
					fi
				    else
				        echo "Error : rc=$status $MKISOFS"
				    fi
				else
				    echo "Error : rc=$status cd `dirname $DATA`"
				fi
				;;
			CUE)
          	     		$DAO_RECORDCMD write $DAO_OPTS --device $WRITER_ADR $DATA
				status=$?
				;;
			*)
				;;
		     esac

                     if [ $status -eq 0 ]
                     then
                          $SVDRPSEND MESG $MEDIA_MSG_OK >> /dev/null 2>&1
                          [ "$POSTACTION" = "DEL" ] && rm -rf $DATA
                          [ "$BURN_DISABLE_EJECT" != "yes" ] && eject $WRITER 2>/dev/null
			  sleep 120
                          [ "$BURN_DISABLE_EJECT" != "yes" ] && eject -t $WRITER 2>/dev/null
			  sleep 10
                     else
                          $SVDRPSEND MESG $MEDIA_MSG_ERROR >> /dev/null 2>&1
                          sleep 5
                          let round=round+1
                          if [ $round -lt $BURN_MAXRETRY ]
	                  then
		            $SVDRPSEND MESG $MEDIA_MSG_RETRY_IN_X_MINUTES >> /dev/null 2>&1
                            sleep 300
	                  fi
                     fi
                 done
	         ;;
	*)
	        echo "Unknown format"
	        ;;
      esac

      rm -rf ${UniqueBURNDIR}
      echo "`date` : Burning session for $CMDLIN done"
      cp $NewJobs $NewJobs.$$
      grep -x -v "$CMDLIN" $NewJobs.$$ > $NewJobs 
      rm $NewJobs.$$

     done
   fi
else
      echo "ERROR : ${BURN_DESTDIR} or ${TEMPDIR} are not writable. $0 exit"
      logger "ERROR : ${BURN_DESTDIR} or ${TEMPDIR} are not writable. $0 exit"
fi
Exit
