#!/bin/sh

# the dvd device
DVDDEV=/dev/dvd
# the mount point of the dvd device
# XXX - generate this from fstab?
DVDDRIVE=/cdrom1
# the size of your DVDR media
DVDRSIZE=4650
# the "i'm done" audio file
WAVE=/music/samples/guitar/blues15.wav

# This script will attempt to backup a DVD to your hard disk and
# prepare it for burning. If the source is less than 4.5GB, it will
# create a straighforward bit for bit backup, which includes all 
# menus, subtitles, etc. Otherwise, it will first strip ALL extras 
# (including subtitles, sadly), and then if necessary shrink the
# main title by the calculated factor.

# TO DO
# 1) Provide option to split DVD instead of stripping and compression
# 2) Provide option to keep subtitles when stripping extras

# USAGE
# dvddup backupdir [imagedir]
# If imagedir is specified, and there is enough disk space at the location,
# the script will create an ISO image from the backed up VOB files.

# REQUIRED programs
# streamanalyze, streamdvd -- http://www.badabum.de/streamdvd.html
# mkisofs, isoinfo -- provided in cdrtools package???
# dvdbackup
# dvdauthor
# something to burn with, e.g. k3b
# libdvdread-dev -- needed to compile streamanalyze
# tcprobe (provided with transcode)

# OPTIONAL programs
# play -- to play a sound once this is done

# SKIP down to numbered code to follow sequence

analyzetrack() {
        awk     '/MPEG/ {VPOS=$2}
                /Audio/ {if (APOS == "") APOS=$2}
                /Factor/ {FACTOR=$3}
        END {
	     printf("FACTOR=%s; APOS=%s; VPOS=%s\n", FACTOR, APOS, VPOS);}'
}

analyzeiso() {
        awk 'BEGIN{minsize="999999"; minname="none"}
	                {if ($12 != "." && $12 != ".." && $12 != "VIDEO_TS" &&
	                        $12 > 0 && $10 >0  && minsize>$10)
                        {minname=$12;minsize=$10}}
             END{printf("%s",minname)}'
}

b4b() {
	echo 2---------------
	echo Creating backup
	echo 2---------------
	dvdbackup -M -i${DVDDEV} -o${OUTFILE} -n backup
	echo 3-------------------------------------------------
	echo "Made backup of dvd at ${OUTFILE}/backup"
	echo Burn the structure using k3b or dvdrecord
	echo 3-------------------------------------------------
}

shrink() {
	echo 2--------------------------------------------------------------------------			
	echo Preparing to shrink
	echo Analyzing titles "(stage 1)"...
	TRACK=$(lsdvd | grep 'Longest' | tail -c 2)
	# XXX - not the right parsing for tcprobe
	#TRACK=$(tcprobe -i ${DVDDEV} 2>&1 | grep 'title set' | tail -c 2)
	echo Analyzing title $TRACK "(stage 2)"...
	eval $(streamanalyze -i ${DVDDEV} -t ${TRACK} 2>&1 | analyzetrack)
	echo Factor: $FACTOR
	# XXX - is -eq the right operator?
	if [ "$FACTOR"="not" ]
	then
        	echo Preparing main title for burning without shrinkage		
		echo This will take a couple of hours
		echo dvdauthor -t -o ${OUTFILE} -f \
	                "'streamdvd -i ${DVDDEV} -t ${TRACK} -s ${VPOS},${APOS} |'";
		echo 2--------------------------------------------------------------------------			
		dvdauthor -t -o $OUTFILE -f \
			"streamdvd -i ${DVDDEV} -t ${TRACK} -s ${VPOS},${APOS} |"
	else
		echo Preparing main title for burning with shrinkage factor $FACTOR
		echo This will take a few hours
		echo dvdauthor -t -o ${OUTFILE} -f \
	                "'streamdvd -i ${DVDDEV} -t ${TRACK} -s ${VPOS},${APOS} -f ${FACTOR} |'";
		echo 2--------------------------------------------------------------------------
		dvdauthor -t -o ${OUTFILE} -f \
			"streamdvd -i ${DVDDEV} -t ${TRACK} -s ${VPOS},${APOS} -f ${FACTOR} |"
	fi
	dvdauthor -T -o ${OUTFILE}
	echo 3----------------------------------------------------
	echo Complete structure has been created at $OUTFILE
	echo Burn the video_ts and audio_ts folders to a dvd
	echo "(e.g. using k3b) and you're done"
	echo 3----------------------------------------------------
}

############################################################
#-------------------------------START 
############################################################

PROG=$(basename $0)

# 1) read in the destination from the command line
if [ -z $1 ]
then
   	echo "Usage: $PROG outfile [imagefile]" 1>&2
   	exit 1
else
	OUTFILE=$1
	# the second parameter (optional) defines where
	# to create an image, if appropriate
	if [ $# -gt 1 ]
	then
		IMAGEFILE=$2
		USEIMAGE=1
	else
		IMAGEFILE=$OUTFILE
		USEIMAGE=0
	fi		
fi
mount $DVDDRIVE
echo Looking at source...
# 2) check the size of the dvd, and the amount of free space in
# the destination
THESIZE=$(df -k $DVDDRIVE | awk '(NR > 1) {printf("%d",$3/1000)}')
FREESPACE=$(df -k $OUTFILE | awk '(NR > 1) {printf("%d",$4/1000)}')
OUTFILESYSTEM=$(df -k $OUTFILE | awk '(NR > 1) {printf("%s",$1)}')
IMAGEFILESYSTEM=$(df -k $IMAGEFILE | awk '(NR > 1) {printf("%s",$1)}')

# 3.1) If the hard disk doesn't have enough space for our purposes
if [ $FREESPACE -lt $DVDRSIZE ] 
then
	echo "Sorry, you don't have enough disk space free at $1"
# 3.2) If the DVD size is 0
elif [ $THESIZE -eq 0 ] 
then
	echo "Can't find movie!"
	echo "Perhaps you haven't put a movie in the DVD drive yet?"
# 3.3) If the free space on the hard disk is > 4500 but less than the dvd size
elif [ $FREESPACE -lt $THESIZE ] 
then 
	echo 1--------------------------------------------------------------
	echo $FREESPACE MBs is free. The movie is $THESIZE MBs.
	echo "You do not have enough free space to copy the movie bit for bit"
	echo "Stripping extras, may need to shrink"
	echo 1--------------------------------------------------------------
	shrink
	SHRUNK=1
# 3.4) If the dvd size is more than one blank dvd	
elif [ $THESIZE -gt $DVDRSIZE ] 
then
	echo 1--------------------------------------------------------------
	echo $FREESPACE MBs is free. The movie is $THESIZE MBs.
	echo "The movie will not fit on one DVD as is (burnables have less"
	echo "capacity.) Stripping extras, may need to shrink."
	echo 1--------------------------------------------------------------
	shrink
	SHRUNK=1
# 3.5) Otherwise do a bit for bit copy
else
	echo 1----------------------------------------------------
	echo $FREESPACE MBs is free. The movie is $THESIZE MBs. 
	echo Copying movie bit for bit. This will take a while.
	echo 1----------------------------------------------------
	b4b
	SHRUNK=0
fi

# 4) If they wish to generate an ISO image, do so
if [ $USEIMAGE -eq 1 ]
then
	# 4.1) Check if the image is to be located on the same filesystem, and
	# whether we have enough space to do so
	echo {$IMAGEFILESYSTEM} and {$OUTFILESYSTEM}	
	if [ $IMAGEFILESYSTEM = $OUTFILESYSTEM ]
	then
		echo Using same filesystem to generate image			
		IMAGESIZE=$(($THESIZE * 2))
		TWICESIZE=$(($DVDRSIZE * 2))
		if [ $TWICESIZE -lt $IMAGESIZE ]
		then
			$IMAGESIZE=$TWICESIZE
		fi	
		IMAGESPACE=$FREESPACE
		echo {$IMAGESIZE} and {$TWICESIZE} and {$IMAGESPACE}
	else
		echo Using different filesystem to generate image
		if [ $THESIZE -lt $DVDRSIZE ]
		then
			IMAGESIZE=$THESIZE
		else
			IMAGESIZE=$DVDRSIZE 
		fi		
		IMAGESPACE=$(df -k $IMAGEFILE | awk '(NR > 1) {printf("%d",$4/1000)}')
		echo {$IMAGESIZE} and {$IMAGESPACE}
	fi

	# 4.2) If we don't have enough space, print a helpful message and finish up
	if [ $IMAGESPACE -lt $IMAGESIZE ] 
	then
		echo 4----------------------------------------------------------------
		echo "Sorry, you don't have enough space on the	file system:"
		echo $IMAGEFILESYSTEM to create an ISO image. You can attempt
		echo to do this yourself using the following command:
		if [ $SHRUNK=0 ]
		then
			echo "mkisofs -dvd-video -o ${IMAGEFILE}/burnme.img ${OUTFILE}/backup/"
		else 
			echo "mkisofs -dvd-video -o ${IMAGEFILE}/burnme.img ${OUTFILE}/"
		fi			
		echo However, I recommend you locate the image file elsewhere.
		echo 4----------------------------------------------------------------
	# 4.3) Else, if we have enough space to create the image, then do so
	else	
		# 4.3.1) Make the image. Depending on whether we shrunk or not, the
		# vob files will be in different folders.
		echo Now starting image creation. This will take a while.
		if [ $SHRUNK=0 ]
		then
		        mkisofs -dvd-video -o ${IMAGEFILE}/burnme.img ${OUTFILE}/backup/
		else
		        mkisofs -dvd-video -o ${IMAGEFILE}/burnme.img ${OUTFILE}/
		fi					
		# 4.3.2) Now check the image file for validity. We make sure that the 
		# first file is VIDEO_TS.BUP.
        	FIRSTFILE=$(isoinfo -i ${IMAGEFILE}/burnme.img -l | analyzeiso)
	        if [ $FIRSTFILE="VIDEO_TS.BUP;1" ]
        	then
        		echo --------------------------------------------------------
        		echo An ISO image has been created at $IMAGEFILE
        		echo You may delete the temporary backup files at $OUTFILE
        		echo "Burn the burnme.img file to DVD (e.g. using k3b) "
        		echo "and you're done"
        		echo --------------------------------------------------------
		else
        		echo -------------------------------------------------------------
        		echo An ISO image has been created at $IMAGEFILE
        		echo "However, it doesn't appear to check out using isoinfo -i,"
        		echo "since the first file in the image is ${FIRSTFILE}; it should"
        		echo "be named VIDEO_TS.BUP;1. If you feel that this is OK, go "
        		echo "ahead and burn the image named burnme.img. The temporary"
        		echo "dvd backup is located at ${OUTFILE}/backup. It might burn"
        		echo "correctly also."
        		echo -------------------------------------------------------------
		fi
	fi
else
	echo Image generation not requested.	
fi
umount $DVDDRIVE
eject $DVDDRIVE
play 
echo Done.
