#!/bin/dash

# To be invoked from optical drive icon's context menu:
# rip2iso <device>
# e.g. rip2iso /dev/sr0

# std localisation stanza
export TEXTDOMAIN=fatdog
. gettext.sh

# $2 can be ommited and then disc label will be used instead
INPUT_DEV="$1"
OUTPUT_FILE="$2"
OUTPUT_DIR="${HOME}/"	# keep the trailing slash!

# Usage
if [ ! "$INPUT_DEV" ]; then
	echo "Usage: $0 <input_device> [output_file]"
	exit
fi

# Preparations
DLG=Xdialog

APPNAME="Rip2Iso"
WORKDIR="/tmp/rip2iso.$USER.$$"
PIPE="$WORKDIR/pipe"
PVPID="$WORKDIR/pvpid"

mkdir -p "$WORKDIR"
mkfifo "$PIPE"
exec 3<>"$PIPE"

trap '[ -d "$WORKDIR" ] && rm -rf "$WORKDIR"; exit' 0 INT HUP TERM

# Get disc info
DISCINFO="$(blkid $INPUT_DEV)"

# No disc or e.g. audio cd
if [ $? -ne 0 ]; then
	$DLG --title "$APPNAME" \
		 --icon="/usr/share/pixmaps/midi-icons/error.xpm" \
		 --infobox "$(gettext "There's no valid disc in the drive!")" 0 0 10000
	exit
fi

# Get destination dir from user and obtain disc label
if [ ! "$OUTPUT_FILE" ]; then
	OUTPUT_DIR=$($DLG --stdout --title "$APPNAME" \
		 --backtitle "$(gettext "Select output directory")" \
		 --dselect "$HOME" 0 0)

	[ $? -ne 0 ] && exit

	DISCLABEL="$(echo $DISCINFO | sed -n 's/.*LABEL="\([^"]*\).*/\1/p')"

	if [ "$DISCLABEL" ]; then
		OUTPUT_FILE="${OUTPUT_DIR}${DISCLABEL}.iso"
	else
		OUTPUT_FILE="${OUTPUT_DIR}Image.iso"
	fi
fi

# Overwrite if already exists?
if [ -e "$OUTPUT_FILE" ]; then
	$DLG --title "$APPNAME" \
		 --icon="/usr/share/pixmaps/midi-icons/question.xpm" \
		 --yesno "$(gettext "Destination file already exists:")\n${OUTPUT_FILE}\n$(gettext "Overwrite?")" 0 0

	[ $? -ne 0 ] && exit
fi

# Initiate progress dialog
(
	$DLG --title "$APPNAME" \
		 --icon="/usr/share/pixmaps/midi-icons/optical48.png" \
		 --gauge "$(gettext "Creating ISO image, please wait...")" 0 0 <"$PIPE"

	if [ $? -ne 0 ]; then
		[ -f "$PVPID" ] &&
		PID=$(cat "$PVPID") &&
		[ ! -z "$PID" ] &&
		kill -0 $PID 2>/dev/null &&
		kill $PID

		rm -f "$OUTPUT_FILE"
	fi
) &

# Rip to ISO
pv -P "$PVPID" -n "$INPUT_DEV" > "$OUTPUT_FILE" 2>"$PIPE"
RETCODE=$?

# Close DLG
echo 101 > "$PIPE"	

# Show final dialog
case $RETCODE in
	0)	$DLG --title "$APPNAME" \
			 --icon="/usr/share/pixmaps/midi-icons/ok.xpm" \
			 --infobox "$(gettext "ISO image has been created successfully:")\n${OUTPUT_FILE}" 0 0 10000	;;
	*)	$DLG --title "$APPNAME" \
			 --icon="/usr/share/pixmaps/midi-icons/error.xpm" \
			 --infobox "$(gettext "Failed to create ISO image!")" 0 0 10000	;;
esac

exit
