#!/bin/sh
# burndvd - contact: mail@tillmann-steinbrecher.de
# GNU GPL

dvdspeed=4

# Device file, for growisofs
devfile="/dev/scd0"

# Device for cdrecord
device="0,0,0"

# Options for growisofs
# growoption= 

# Options for cdrecord
# option=

if [ "$1" == "" ] ; then
    echo "Usage: burndvd <directory name>"
    echo "       burns the content of this directory on a DVD+R(W)"
    exit;
fi

cd $1 >/dev/null 2>&1

if [ $? -ne 0 ] ; then
        echo "Error: Can't change to directory $1"
        exit 1
fi

echo -n "Checking for .iso / .img file..."

# NOTE!!! You need to have extended globbing in bash turned on;
# run "shopt extglob" to find out

shopt -s extglob
ls *.*(img|iso|IMG|ISO)>/dev/null 2>&1

if [ $? -eq 0 ] ; then
    imgname=`ls *.*(img|iso|IMG|ISO) | head -n 1`
    echo "found."
    echo "Burning DVD using image file $imgname"
    cdrecord -dao dev=$device -driveropts=burnfree speed=$dvdspeed $imgname
else
   echo "not found."
   growisofs -speed=$dvdspeed -joliet-long -Z $devfile -J -r .
   result=$?
   
   # the following is an ugly workaround
   # In some cases the first writing attempt fails when speed setting is present.
   # If growisofs is called again after that, it will write alright, using the
   # speed setting from the previous call (WTF!). We detect this situation, and
   # if necessary call growisofs twice. Maybe this is fixed in newer growisofs
   # and/or firmware versions. In any case, if the problem doesn't occur the
   # workaround code isn't used anyways.
   
   if [ $result == 150 ] ; then
     echo "Trying without speed setting."
     growisofs $growoption -joliet-long -Z $devfile -J -r .
   fi
fi

echo "Write finished."

cd ..
