#!/bin/bash

# This script dumps the specified Filesystem via dump on a CD/DVD
# DISK_CAPACITY defines the capacity in MB per disk.
# The script's own name $0 is passed via the -F option of dump
# When using cdrecord/dvdrecord and at least for my DVD-Recorder (a PHILIPS
# DVR-A03) it is necessary to define the tracksize for the next track before
# the DVD is written. This is done via the -tsize option of cdrecord. Since
# tsize takes its arguments in Bytes, the shell cannot compute the value
# correctly anymore (value too high), so I use bc.

# Set this to 4300 for DVD and 650 or 700 for CD
#DISK_CAPACITY=10	# testing
#DISK_CAPACITY=650
DISK_CAPACITY=4300

BSIZE="$(echo "$DISK_CAPACITY*1024" | bc -l )"
TSIZE="$(echo "$DISK_CAPACITY*1024*1024" | bc -l )"

# This is used for testing
#RECORD_BIN="dd of=/dev/null bs=1k if="

# This is for writing to CD with cdrtools, this uses track-at-once mode
# in case cdrtools does not support disk-at-once with your burner
#RECORD_BIN="/usr/bin/cdrecord dev=0,0,0 fs=64M speed=2 -eject -tao -pad -tsize=$TSIZE -data "

# This is for writing to DVD with cdrtools with DVD support, this has to
# use disk-at-once mode.
#RECORD_BIN="/usr/bin/cdrecord dev=0,0,0 fs=64M speed=2 -eject -dao -pad -tsize=$TSIZE -data "

# This is for writing to DVD with growisofs
RECORD_BIN="/usr/bin/growisofs -Z /dev/dvd="

FIFO="/tmp/dump.$$.fifo"
DUMP="/sbin/dump"

cleanup() {
	rm -f $FIFO
}

# exit on errors
set -e

write_output() {
	# supplied info from "dump -F":
	# $1 = filename
	# $2 = sequence number
	echo "Please insert disk No. $(($2+1))"
	ANSWER=""
	while [ "$ANSWER" != "y" ] ; do
		echo -n "Is the disk ready? (y/n) "
		read  </dev/tty ANSWER
		if [ "$ANSWER" = "y" ] ; then
			(${RECORD_BIN}${1}) &
			return 0
		elif [ "$ANSWER" = "n" ] ; then
			EXIT=""
			echo -n "Do you really want to exit? (y/n) "
			read </dev/tty EXIT
			if [ "$EXIT" = "y" ] ; then
				return 1
			fi
		fi
	done
}

if [ "$#" = "0" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo >&2 "Usage: $0 <dump options>"
	echo >&2 "See 'man dump' for dump options"
	echo >&2 "the dump options -F -f -B are not required and are overridden"
	exit 1
fi

set -m	# We need proper job control

if [ "$#" = "2" ] && [ -p "$1" ]; then
	write_output "$@" || (kill $$ >/dev/null 2>&1; exit 1)
	exit 0
else
	mkfifo $FIFO
	trap cleanup 0
	if write_output "$FIFO" "0"; then
		if $DUMP "$@" -F "$0" -f "$FIFO" -B$BSIZE; then
			echo "Waiting for background writing process to complete"
			wait %			# Wait for the background writing process
		else
			kill % >/dev/null 2>&1	# or kill it
			exit 1
		fi
		exit 0
	else
		kill % >/dev/null 2>&1	# Kill the background writing process
		exit 1
	fi
fi
