#!/bin/bash
###############################################################################
# About: The purpose of this script is to easy DVD copying in linux.          #
# Required: lsdvd (http://acidrip.thirtythreeandathird.net)                   #
#           streamdvd & streananalyze (http://www.badabum.de/streamdvd.html)  #
#           dvdauthor (http://sourceforge.net/projects/dvdauthor/)            # 
#           cdrtools & cdrecord-prodvd (http://www.fokus.gmd.de/research/cc/glone/employees/joerg.schilling/private/cdrecord.html)
# Author: Todor T. Zviskov (a.k.a. Warder) - http://warder.ath.cx:81/         #
# License: GPL-2 - http://www.gnu.org/licenses/gpl.txt                        #
# Version: 0.1                                                                #
# Changes: none                                                               #
###############################################################################

#################################################
# User Defined Variables - change to your needs #
#################################################

#DVD Reader
READER="/dev/dvd"
#DVD Burner - eg. 0,0,0
BURNER="ATAPI:0,0,0"
#TEMP directory (at least 9.5GB free space)
TMP_DIR="/tmp"
#ISO image name
IMAGE="image.iso"


######################
# Script Starts Here #
######################

#clean any lefovers
rm -rf $TMP_DIR/movie

echo "Finding the longest track on DVD..."
#Find longest track to rip
TRACK=`lsdvd $READER 2>&1|grep -i longest|cut -d ":" -f2|awk '{print $1}'`

echo "Finding the requant factor..."
#Get requant factor
FACTOR=`streamanalyze -i $READER -t $TRACK -s 0xe0,0x80 2>&1|grep -i factor|cut -d ':' -f2| awk '{print $1$2}'`

if [ "$FACTOR" = "notneeded" ]; then
	ans="Y"
	echo -ne "\nRequantizing is not needed. Read the DVD with dd? [Y/n]: Y\b"
	read ans
	if [ "$ans" = "Y" ]; then
		echo "Reading the DVD with dd, please wait..."
		dd if=$READER of=$TMP_DIR/$IMAGE
	elif [ "$ans" = "y" ]; then
		echo "Reading the DVD with dd, please wait..."
		dd if=$READER of=$TMP_DIR/$IMAGE
	else
		echo "Reading the track..."
		dvdauthor -t -o $TMP_DIR/movie -f \
			"streamdvd -i ${READER} -t ${TRACK} -s 0xe0,0x80 |"
		dvdauthor -T -o $TMP_DIR/movie
		echo "Creating the ISO image"
		mkisofs -r -dvd-video -udf -o $TMP_DIR/$IMAGE $TMP_DIR/movie/
	fi
else
	echo "Reading the track..."
	dvdauthor -t -o $TMP_DIR/movie -f \
		"streamdvd -i ${READER} -t ${TRACK} -s 0xe0,0x80 -f ${FACTOR}|"
	dvdauthor -T -o $TMP_DIR/movie
	echo "Creating the ISO image"
	mkisofs -r -dvd-video -udf -o $TMP_DIR/$IMAGE $TMP_DIR/movie/


fi

echo "Removing directory with ripped track..."
rm -rf $TMP_DIR/movie

echo -n "Insert a blank DVD in your DVD Burner and press the Enter key to burn $TMP_DIR/$IMAGE (Ctrl-C to cancel)"
read
cdrecord-wrapper.sh dev=$BURNER -v -eject -dao driveropts=burnproof $TMP_DIR/$IMAGE
echo -n "Delete image $TMP_DIR/$IMAGE (Ctrl-C to cancel)?"
echo "Deleting image, please wait..."
read
rm $TMP_DIR/$IMAGE
echo "All done."
