#!/bin/bash

##############################################################################
# DVD2ISO.SH - Copies a DVD to an ISO image. Does not attempt to transcode or
#              otherwise alter the DVD contents.
#              vrai@acherondevelopment.com
#
# Requires packages:
#	Gentoo: lsdvd dvdbackup dvdrtools
#
# Published under the GNU Public License: http://www.gnu.org/copyleft/gpl.html
#
# $Id: dvd2iso.sh,v 1.2 2005/01/08 18:33:31 vrai Exp $


##############################################################################
# Global variables

TMPDIR=/tmp
DVDDEVICE=/dev/dvd

LSDVD="lsdvd"
DVDBACKUP="dvdbackup -M -o $TMPDIR -i "
MKISOFS="mkisofs -dvd-video -o"

LSDVDTAG="Disc Title:"


##############################################################################
# Functions

function FatalError
{
	echo $1
	exit
}

function DeleteDirectory
{
	if [ -e "$1" ]; then
		rm -rf $1
	fi
}


##############################################################################
# Script

# Get the command line options
while getopts ":o:d:" option; do
	case $option in
		o) ISOPATH=$OPTARG   ;;
		d) DVDDEVICE=$OPTARG ;;
	esac
done

if [ -z "$ISOPATH" ]; then
	FatalError "Usage: `basename $0` -o output_iso_path [ -d dvd_device ]"
fi

# Get the DVD name
DVDNAME=`$LSDVD $DVDDEVICE 2>/dev/null | grep "$LSDVDTAG" | sed 's/[^:]*:[ \r\t\n]*//'`
if [ -z "$DVDNAME" ]; then
	FatalError "Unable to retrieve DVD name using $LSDVD"
fi

# Copy the DVD to a temporary directory
DVDDIR="$TMPDIR/$DVDNAME"
DeleteDirectory "$DVDDIR"
$DVDBACKUP $DVDDEVICE

# Use the DVD to make an ISO
$MKISOFS $ISOPATH $DVDDIR
DeleteDirectory "$DVDDIR"
