#!/bin/sh
# (C) 2011, Tim Schuermann, Linux New Media AG

# This script was originally written in German.
# Test this English version carefully.

# Help for script
if [ $1 ]; then
	echo '*'
	echo '* If you start convert.sh without parameters, the script uses the following standards:'
	echo '*	Default: dvd_directory=/dev/dvd'
	echo '*	Default: video_folder=~/Videos'
	echo '* Open convert.conf in an editor to change the defaults.' 
	echo '*'
	exit 0
else
	echo 'Help for ./convert.sh -h'
	continue	
fi
# Import config.conf base variables (/dev/dvd and ~/Videos):
. ./config.conf

# For unlimited number of DVDs do:
while :;do

	# 1. step: Eject DVD:
	echo "Eject DVD"
	eject ${dvd_directory}
	sleep 2; # required to prevent access errors.

	# 2. step: Find new DVD:
	echo "Wait for media"
	while :;do
		# when lsdvd returns a result, the DVD is ready
		res=$(lsdvd ${dvd_directory} -c 2> /dev/null | grep -c "Longest")
		case "${res}" in
		0) # no DVD inserted, wait a moment:
			echo -n "."; 
			sleep 1;;
		1) # 3. step: Create filename, find main track:

			# filename is label for DVD:
			#label=$(udisks --show-info ${dvd_directory} | grep -m 1 "^  label:" | sed 's/ *label: *\(.*\)/\1/';)
			label=$(lsdvd -c ${dvd_directory} 2> /dev/null | grep -m 1 "^Disc Title" | sed 's/Disc Title: *\(.*\)/\1/';) 
			echo "\nDVD $label found"
			if [ -z "$label" ] ; then 
				label="dvd_$(date +'%m-%d-%Y_%k-%M-%S')" 
			fi 
				# If no label, use another name
				filename="${label}"
			
			# Identify main track (mostly works, but not always)
			maintrack=$(lsdvd -c ${dvd_directory} | grep "Longest" | cut -d " " -f 3)
			echo "Track ${maintrack} seems to be the feature film."

			# check that corresponding file exists:
			count=0
			while [ 1 ]
			do
				for file in "${video_folder}/${filename}.*"; do
					if [ -f $file ]; then
						# the file exists, 
						# increment count by one and try again:
						# echo "$directory/$filename exists"
						count=$((count+1));
						filename="${label}${count}";
						break; # exit for-loop
					else
						# file doesn't exist yet, thus filename applies:
						#echo "$directory/$filename doesn't exist yet"
						break 2; # exit while-loop
					fi
				done
			done

			# 4. step: Read and encode:
			unlink frameno.avi 2> /dev/null
			mencoder dvd://${maintrack} \
				-dvd-device ${dvd_directory} \
				-alang en -nosub \
				-ovc x264 \
				-x264encopts crf=20:subq=6:frameref=5:partitions=all:8x8dct=1:me=umh:bframes=3:weight_b=1:keyint=25 \
				-oac mp3lame -lameopts aq=0:q=0 \
				-o "${video_folder}/${filename}.avi"
			break;;
		esac
		
	done
	echo "Done."
done
exit 0 
