#!/bin/sh
# Version: 0.2.0
# Author: Dimitrios Dimitrakos mail@dimitrios.de
# $Id: ripcda.sh,v 1.10 2005/01/06 18:23:15 dimi Exp $
#
LANG=C
#set -x
vco_user=`id -n -u`
homedir=`cat /etc/passwd|grep "^${vco_user}:"|cut -f6 -d ':'`
[ -f $homedir/.vdrconvert/vdrconvert.env ] && . $homedir/.vdrconvert/vdrconvert.env
[ -r $homedir/.vdrconvert/ripcda.env ] && . $homedir/.vdrconvert/ripcda.env

RM=rm

PIDFILE="$VCORUNDIR/`basename ${0}.pid`"
echo "$$" >> $PIDFILE

trap do_clean SIGINT SIGQUIT SIGTERM 
do_clean() {
	if [ -f $PIDFILE ]
	then
		TEMPPID=$LTEMPDIR/`basename $PIDFILE`.$$
		mv $PIDFILE $TEMPPID
		status=$?
		if [ $status -eq 0 ]
		then
			[ `cat $TEMPPID|wc -l` -gt 0 ] && cat $TEMPPID|grep -v $$ > $PIDFILE 
		fi
		[ -f $TEMPPID ] && $RM $TEMPPID
	fi
	echo "End."
	exit
}

Exit() {
	do_clean
}

NewJobs=$1
JOBFIL=$2
LOGFILE=$3

# clean spool
[ -f "$VCOQUEUEDIR/${JOBFIL}" ] && > $VCOQUEUEDIR/${JOBFIL}

[ "$CDA_DEBUG" = "yes" ] && set -x 

printf "`date +"%d-%m-%2Y %T"` : Session %s begin\n" "$0"

### XXX For test only
#TEMPDIR=/tmp
[ -z "$TEMPDIR" ] && TEMPDIR=/tmp
[ -z "$LOGFILE" ] && LOGFILE=/var/log/ripcda.log
[ -z "$DESTDIR" ] && DESTDIR=.
#########

[ -z "$CDA_DESTDIR" ]       && CDA_DESTDIR=$DESTDIR/cda
[ -z "$CDA_CDPLAYER" ]      && CDA_CDPLAYER=`cat /proc/sys/dev/cdrom/info|grep "drive name:"|cut -f2- -d ':'`
[ -z "$CDA_MP3_OPTS" ]      && CDA_MP3_OPTS="-b 192 -h --resample 44100"
[ -z "$CDA_MODE" ]          && CDA_MODE="mp3"
[ -z "$PRIO" ]              && PRIO=15
[ -z "$LAME" ]              && LAME=lame
[ -z "$OGG_ENC" ]           && OGG_ENC="oggenc"
[ -z "$CDPARANOIA" ]        && CDPARANOIA="cdparanoia"
[ -z "$OGG_OPTS" ]          && OGG_OPTS="--resample 44100 -M192 -b128"
[ -z "$CDA_RECODE" ]        && CDA_RECODE="no"
[ -z "$CDA_DISABLE_EJECT" ] && CDA_DISABLE_EJECT="no"
[ -z "$CDA_ASK_IF_MULTI" ]  && CDA_ASK_IF_MULTI="no"
[ -z "$CDA_INTERACTIV" ]    && CDA_INTERACTIV="no"

# XXX Read this from a separate file for access to all vdrconvert tools
case $VDRCONVERT_LANG in
	de|DE )
		[ -z "$MEDIA_MSG_OK" ]                 && MEDIA_MSG_OK="Medium wurde erfolgreich erstellt"
		[ -z "$MEDIA_MSG_ERROR" ]              && MEDIA_MSG_ERROR="Fehler beim Schreibvorgang"
		[ -z "$MEDIA_MSG_INSERT_CD" ]          && MEDIA_MSG_INSERT_CD="Bitte legen sie ein CD Medium ein"
		[ -z "$MEDIA_MSG_INSERT_CD" ]          && MEDIA_MSG_REMOVE_CD="Bitte CD entfernen"
		[ -z "$MEDIA_MSG_INSERT_DVD" ]         && MEDIA_MSG_INSERT_DVD="Bitte legen sie ein DVD Medium ein"
		[ -z "$MEDIA_MSG_START_FORMAT" ]       && MEDIA_MSG_START_FORMAT="Medium wird geloescht"
		[ -z "$MEDIA_MSG_ISO_READYTOBURN" ]    && MEDIA_MSG_ISO_READYTOBURN="Isodatei ist fertig zum Brennen"
		[ -z "$MEDIA_MSG_START_WRITE_IMAGE" ]  && MEDIA_MSG_START_WRITE_IMAGE="Imagedatei wird gebrannt"
		[ -z "$MEDIA_MSG_RETRY_IN_X_MINUTES" ] && MEDIA_MSG_RETRY_IN_X_MINUTES="Wiederholung in 5 Minuten"
		;;
	*)
		[ -z "$MEDIA_MSG_OK" ]                 && MEDIA_MSG_OK="Media was successfully detected"
		[ -z "$MEDIA_MSG_ERROR" ]              && MEDIA_MSG_ERROR="Failure to write"
		[ -z "$MEDIA_MSG_INSERT_CD" ]          && MEDIA_MSG_INSERT_CD="Please insert CD"
		[ -z "$MEDIA_MSG_INSERT_CD" ]          && MEDIA_MSG_REMOVE_CD="Please remove CD"
		[ -z "$MEDIA_MSG_INSERT_DVD" ]         && MEDIA_MSG_INSERT_DVD="Please insert DVD"
		[ -z "$MEDIA_MSG_START_FORMAT" ]       && MEDIA_MSG_START_FORMAT="Beginning to format medium"
		[ -z "$MEDIA_MSG_ISO_READYTOBURN" ]    && MEDIA_MSG_ISO_READYTOBURN="ISO ready to burn"
		[ -z "$MEDIA_MSG_START_WRITE_IMAGE" ]  && MEDIA_MSG_START_WRITE_IMAGE="Starting to write image"
		[ -z "$MEDIA_MSG_RETRY_IN_X_MINUTES" ] && MEDIA_MSG_RETRY_IN_X_MINUTES="Retry in 5 minutes"
		;;
esac	

[ -z "${JOBFIL}" ] && LTEMPDIR=${TEMPDIR}/${JOBFIL} || LTEMPDIR=${TEMPDIR}/ripcda
[ -d $CDA_DESTDIR ] || mkdir -p $CDA_DESTDIR
[ -d $LTEMPDIR ] || mkdir -p $LTEMPDIR

printf "Tempdir     = %s\n" "${LTEMPDIR}"
printf "Destination = %s\n" "${CDA_DESTDIR}"
printf "Logfile     = %s\n" "${LOGFILE}"
if [ -w ${LTEMPDIR} -a -w ${CDA_DESTDIR} ]
then

    TEMPFILE=$LTEMPDIR/cdafile.tmp.$$

    album=""
    genre=""
    let numtitles=0
    let try=0

    for Device in $CDA_CDPLAYER
    do
	cdplayer=/dev/$Device
	echo "Try Player $cdplayer"
	cdstat=`lsof $cdplayer`
	if [ -z "$cdstat" -a `mount|cut -f1 -d ' '|grep "^${cdplayer}"|wc -l` -eq 0 ]
	then
		[ -x "$SVDRPSEND" ] && $SVDRPSEND MESG "<$Device>" $MEDIA_MSG_INSERT_CD >> /dev/null 2>&1
		echo "$MEDIA_MSG_INSERT_CD $cdplayer"
		[ "$CDA_DISABLE_EJECT" != "yes" ] && eject $cdplayer 2>/dev/null
		sleep 15
		[ "$CDA_DISABLE_EJECT" != "yes" ] && eject -t $cdplayer 2>/dev/null
		sleep 5

		if [ -x "$VDRCONVERTBINDIR/cddb.pl" ]
		then
			$VDRCONVERTBINDIR/cddb.pl -c ${cdplayer} > ${TEMPFILE} 2>&1  
		else
			echo "Be sure cddb.pl ar set to :"
			echo "\$config{input}=0;   # 0: no user interaction"
			echo "\$config{multi}=1;   # 1: do not ask user and get all of them"
			echo "Otherwise $0 will hang."
			cddb.pl -c ${cdplayer} > ${TEMPFILE} 2>&1
		fi
		status=$?
		if [ $status -eq 0 ]
		then
			if [ -f $TEMPFILE ]
			then
				let sentry=1
				entrys=`cat $TEMPFILE|grep "title"|sort -u|wc -l`
				if [ $entrys -gt 1 -a "$CDA_ASK_IF_MULTI" = "yes" ]
				then
					let i=1
					[ $entrys -ge $i ] && printf " Nr. Titel <Interpret>"
					while [ $entrys -ge $i ]
					do
						printf " %02d) %s\n" $i  "`cat $TEMPFILE|grep "title"|sed 's/title://g'|tail -n $i|head -n 1`"
						let i=i+1
					done
					echo ""
					echo -n "Find multiple entrys. Select one : "
					read sentry
				fi

				album=`cat $TEMPFILE|grep "title"|tail -n $sentry|head -n 1|cut -f2 -d ':'|cut -f2- -d ' '|sed 's/\//-/g'`
				genre=`cat $TEMPFILE|grep "genre"|tail -n $sentry|head -n 1|cut -f2 -d ':'|cut -f2- -d ' '|sed 's/\//-/g'`
				year=`cat $TEMPFILE|grep "year"|tail -n $sentry|head -n 1|cut -f2 -d ':'|cut -f2- -d ' '`
				snumtitles=`cat $TEMPFILE|grep "trackno"|tail -n $sentry|head -n 1|cut -f2 -d ':'|awk '{ print $1 }'`
				[ -n "$snumtitles" ] && let numtitles=snumtitles
				let Number=0
				while [ $Number -lt $numtitles ]
				do
					artist[Number]=""
					index=`printf "track %d:" $[ Number+1 ]`
					Title[Number]=`cat $TEMPFILE|grep "$index"|tail -n $sentry|head -n 1|cut -f2 -d ':'|sed 's/\//-/g'|cut -f2- -d' '`
					[ -z "${Title[Number]}" ] && Title[Number]=`printf "track-%02d" $[ Number+1 ]`
					artist[Number]=`cat $TEMPFILE|grep artist|tail -n $sentry|head -n 1|cut -f2 -d ':'|cut -f2- -d ' '|sed 's/\//-/g'`
					if [ "${artist[Number]}" = "Various" -o "${artist[Number]}" = "various" ]
					then
						artist[Number]=`cat $TEMPFILE|grep "$index"|tail -n $sentry|head -n 1|cut -f2 -d ':'|sed 's/ - /\//g'|cut -f1 -d '/'|cut -f2- -d' '`
						Title[Number]=`cat $TEMPFILE|grep "$index"|tail -n $sentry|head -n 1|cut -f2 -d ':'|sed 's/ - /\//g'|cut -f2 -d '/'|cut -f2- -d' '`
					fi
					let Number=Number+1
				done
			fi
		else
				snumtitles=`$CDPARANOIA -d $cdplayer -vsQ 2>&1|tail -n 3|head -n 1|awk '{print $1}'|cut -f1 -d '.'`
				[ -n "$snumtitles" ] && let numtitles=snumtitles
				let Number=0
				while [ $Number -lt $numtitles ]
				do
					Title[Number]=`printf "track-%02d" $[ Number+1 ]`
					let Number=Number+1
				done
		fi

		man="no"
		if [ $numtitles -gt 0 ]
		then
			let try=1
			if [ -z "$album" -a "$CDA_INTERACTIV" = "yes" ]
			then
				echo -n "Manualy enter Missing informations ? <yes/no> "
				read man
				if [ "$man" = "yes" ]
				then
					echo -n "Album : "
					read album
					echo -n "Genre : "
					read genre
					echo -n "Year : "
					read year
				else
					album="UNKNOWN"
				fi
			fi

			let Number=0
			while [ $Number -lt $numtitles ]
			do
				if [ -z "${artist[Number]}" -o -z "${Title[Number]}" ]
				then
					if [ "$man" = "yes" ]
					then
						echo -n " Titel $[ $Number+1 ]  : "
						read Title[Number]
						echo -n " Artist $[ $Number+1 ] : "
						read artist[Number]
					else
						artist[Number]="UNKNOWN"
					fi
				fi
				let Number=Number+1
			done
			echo ""
			echo ""
			echo "-------------"
			echo "|  CD-Info  |"
			echo "-------------"

			printf "Album\t: %s\n" "$album"
			printf "Genre\t: %s\n" "$genre"
			printf "Year\t: %s\n\n" "$year"
			let Number=0
			while [ $Number -lt $numtitles ]
			do
				printf " %02d) %s <%s>\n" $[ $Number+1 ] "${Title[Number]}" "${artist[Number]}"
				let Number=Number+1
			done
			echo ""

			LDEST=""
			status=0
			echo "Try convert $numtitles tracks to ${CDA_MODE} format."
			[ -x "$SVDRPSEND" ] && $SVDRPSEND MESG "Try convert $numtitles tracks to ${CDA_MODE} format." >> /dev/null 2>&1

			oalbum=$album
			[ -z "$genre" ] && LDEST=$CDA_DESTDIR/$oalbum || LDEST=$CDA_DESTDIR/$genre/$oalbum

			let Number=0
			while [ $Number -lt $numtitles ]
			do
				if [ $Number -eq 0 ]
				then
					if [ ! -d "$LDEST" ]
					then
						DEST="$LDEST"
						mkdir -p "$DEST"
					else
						let index=1
						until [ ! -d "$DEST-${index}" ]
						do
							let index=index+1
						done
						DEST="$LDEST-${index}"
						mkdir -p "$DEST"
						album="$album-${index}"
					fi
				fi

				if [ -d "$DEST" ]
				then
					index=`printf "track-%02d" $[ Number+1 ]`
					echo -n "convert $index to : ${Title[Number]} "
					[ -x "$SVDRPSEND" ] && $SVDRPSEND MESG "convert ${Title[Number]}" >> /dev/null 2>&1
					let track=Number+1	
					[ -z "$genre" ] && DFILE=$album || DFILE=$genre/$album
					case $CDA_MODE in
						ogg)
							nice -n $PRIO  $CDPARANOIA -d $cdplayer $track-$track -w - -e 2>/dev/null | $OGG_ENC \
								-N $track \
								-t "${Title[Number]}" \
								-l "$oalbum" \
								-a "${artist[Number]}" \
								-G "$genre" \
								$OGG_OPTS \
								- \
								-o "$DEST/${Title[Number]}.ogg" > $TEMPFILE 2>&1
							status=$?
							if [ $status -ne 0 ]
							then # Try without genre
								nice -n $PRIO  $CDPARANOIA -d $cdplayer $track-$track -w - -e 2>/dev/null | $OGG_ENC \
									-N $track \
									-t "${Title[Number]}" \
									-l "$oalbum" \
									-a "${artist[Number]}" \
									$OGG_OPTS \
									- \
									-o "$DEST/${Title[Number]}.ogg" > $TEMPFILE 2>&1
								status=$?
							fi
							[ $status -eq 0 ] && echo "$DFILE/${Title[Number]}.ogg" >> "$CDA_DESTDIR/${oalbum}.m3u"
							;;
						mp3)
							nice -n $PRIO $CDPARANOIA -d $cdplayer $track-$track -w - -e 2>/dev/null | $LAME \
								--ta "${artist[Number]}" \
								--tl "$oalbum" \
								--tg "$genre" \
								--ty "$year" \
								--tt "${Title[Number]}" \
								--tn $track \
								--add-id3v2 \
								$CDA_MP3_OPTS \
								- \
								"$DEST/${Title[Number]}.mp3" > $TEMPFILE 2>&1
							status=$?
							if [ $status -ne 0 ]
							then # Try without genre
								nice -n $PRIO $CDPARANOIA -d $cdplayer $track-$track -w - -e 2>/dev/null | $LAME \
									--ta "${artist[Number]}" \
									--tl "$oalbum" \
									--ty "$year" \
									--tt "${Title[Number]}" \
									--tn $track \
									--add-id3v2 \
									$CDA_MP3_OPTS \
									- \
									"$DEST/${Title[Number]}.mp3" > $TEMPFILE 2>&1
								status=$?
							fi
							[ $status -eq 0 ] && echo "$DFILE/${Title[Number]}.mp3" >> "$CDA_DESTDIR/${oalbum}.m3u"
							;;
						*)
							echo "ERROR : Unknown mode $CDA_MODE"
							logger "ERROR : Unknown mode $CDA_MODE"
							;;
					esac
					echo " <--> Done."
				fi
				let Number=Number+1
			done
		else
			echo "ERROR :  no titles found"
			logger "ERROR :  no titles found"
		fi
		if [ $try -eq 1 ]
		then
		    [ -x "$SVDRPSEND" ] && $SVDRPSEND MESG $MEDIA_MSG_REMOVE_CD >> /dev/null 2>&1
		    echo "$MEDIA_MSG_REMOVE_CD"
		    [ "$CDA_DISABLE_EJECT" != "yes" ] && eject $cdplayer 2>/dev/null
		    sleep 15
		    [ "$CDA_DISABLE_EJECT" != "yes" ] && eject -t $cdplayer 2>/dev/null
		    break
		fi
	else
	    echo "Player $cdplayer are not available at the moment"
	    echo $cdstat
	fi
    done
    [ -f "$TEMPFILE" ] && rm $TEMPFILE
else
    echo "Bitte die Schreibrechte für ${LTEMPDIR} und ${CDA_DESTDIR} überprüfen. Keine verarbeitung möglich"
fi
printf "`date +"%d-%m-%2Y %T"` : Session %s end\n" "$0"
Exit
