#!/usr/bin/env bash

# This file contains the functionality for audio CD burning

# This function lets you swap cds if you only have one device.
# (CDwriter and CDreader is same device.)

# Slightly rewritten for cdparanoia instead of cdda2wav
insert_new_CD()
{
	while true; do
		echo $bb_am_enter_2
		read temp
		if [[ "$temp" = "" ]]; then
			break
		else
			continue
		fi
	done
}


# A little function that looks for mp3s
check_for_mp3s()
{
    cd ${BBBURNDIR}
    if [ $(find ${BBBURNDIR} -iname "*.[Mm][Pp]3" | wc -l) -gt 0 ]; then
	${BBROOTDIR}/convert/convert_mp3s.sh
    else
	echo
	echo "$bb_am_nomp3s${BBBURNDIR}"
    fi
}

# A function that checks for ogg files
check_for_oggs()
{
    cd ${BBBURNDIR}
    if [ $(find ${BBBURNDIR} -iname "*.[Oo][Gg][Gg]" | wc -l) -gt 0 ]; then
	${BBROOTDIR}/convert/convert_oggs.sh	
    else
	echo
	echo "$bb_am_nooggs${BBBURNDIR}"
    fi
}

# A function that checks for flac files
check_for_flacs()
{
    cd ${BBBURNDIR}
    if [ $(find ${BBBURNDIR} -iname "*.[Ff][Ll][Aa][Cc]" | wc -l) -gt 0 ]; then
	${BBROOTDIR}/convert/convert_flacs.sh
    else
	echo
	echo "$bb_am_noflacs${BBBURNDIR}"
    fi
}


# A function that adjust the volume of wav
# audio files to a standard volume level.
normalization()
{
	if [[ "$BBNORMALIZE" = "yes" ]]; then
		cd ${BBBURNDIR}
		for i in *.wav; do
			echo;echo -e "${BBTABLECOLOR}|>${BBSUBCOLOR}$bb_am_norm_1$i...${BBCOLOROFF}";
			${BB_NORMCMD} -v -m "$i";
		done
	fi
}

# Function that valide the input of "y" or "n".
conf_yes_no()
{
	unset ANSWER
	while [ "${ANSWER}" != 'y' ] && [ "${ANSWER}" != 'n' ]; do 
		echo -n $bb_am_conf_2
		read ANSWER
	done
}

# Function that control errors.
conf_error()
{
	STDERROR=$?
	# If there is any error return to main menu.
	if [[ ${STDERROR} -ne 0 ]]; then
		echo -e "${BBTABLECOLOR}$bb_am_err_1${BBCOLOROFF}"
		wait_for_enter
		exit
	fi
}

# Simple function that valide confirmation of song names.
confirmation()
{
	echo
	if [[ ! -f "${BBBURNDIR}/song_name.txt" ]]; then
		exit
	else
		echo -e "${BBTABLECOLOR}|>${BBMAINCOLOR}$bb_am_conf_1${BBCOLOROFF}"
		cat -n ${BBBURNDIR}/song_name.txt
		echo -e "${BBSUBCOLOR}"
		conf_yes_no		# Valid input.
		echo -e "${BBCOLOROFF}"	  
		if [[ ${ANSWER} = 'n' ]]; then
			rm -f ${BBBURNDIR}/song_name.txt
			rm -f ${BBBURNDIR}/tracks.txt
			exit
		fi
	fi
}

# Function for interactive naming of files.
named()
{
	# Delete old lists of songs rip.
	rm -f ${BBBURNDIR}/*.txt	  
	# Show some info
	echo -e "${BBSUBCOLOR}$bb_am_named_1${BBCOLOROFF}"
	sleep 1s
	${BB_CDAUDIORIP} -d ${BBCDROM} -vQ
	# If there is any error return to main menu.
	conf_error	  
	TRACK=0
	while [ "${TRACK}" != "" ]; do
		echo;echo -en "${BBMAINCOLOR}$bb_am_named_2"
		echo;echo -en "${BBMAINCOLOR}$bb_am_named_3${BBTABLECOLOR}|>${BBCOLOROFF} "
		read TRACK

		if [ "${TRACK}" != "" ]; then
			# Only permit integer numbers standing the format in the numbers of back prompt.
			number_track=`printf '%02d' ${TRACK}`			
			# This line puts track numbers of the input standard into tracks.txt.	
			echo "${number_track}" >> ${BBBURNDIR}/tracks.txt
		else
			# If nothing is entered at the prompt then exit loop.
			continue
		fi

		echo; echo -e "${BBMAINCOLOR}$bb_am_named_4"
		echo -e "${BBMAINCOLOR}$bb_am_named_5"
		echo -en "${BBMAINCOLOR}$bb_am_named_6${number_track} ${BBTABLECOLOR}|>${BBCOLOROFF} "
		read song_name

		# Put song name into a temporary file for later manipulation by sed
		tempfile=$(mktemp -p ${BBBURNDIR})
		echo ${song_name} >> tempfile

		# If the song_name variable = space blank then, change  
		# fill that with the number of the track to ripped.
		if [[ "${song_name}" = "" ]]; then 
			song_name=`echo "${number_track}.-Track"`
		else
			# If the song_name variable contained some signs and caracters specials, 
			# that difficulty the naming in bash shell, to be equal to nothing.
			# Read sed man page to see how it work.
			# Change by Casper
			song_name=$(sed 's/[()?¿*\/&]//g' tempfile)
		fi

		# Delete temporary file and add song name to a text file
		rm tempfile
		echo ${song_name} >> ${BBBURNDIR}/song_name.txt
	done
}

# Function rip the tracks or songs selects.
rip()
{
	confirmation
	cd ${BBBURNDIR}
	track=0	
	while [ "${track}" != "" ]; do
  		# Read the track to rip of the files in temp directory.
		track=`sed -ne '1p' ${BBBURNDIR}/tracks.txt`
		if [[ "${track}" = "" ]]; then
			continue
		else
			echo -e "${BBTABLECOLOR}|>${BBSUBCOLOR}$bb_am_rip_1${track}...${BBCOLOROFF}"
			# Begin Rip.	
			${BB_CDAUDIORIP} -d ${BBCDROM} ${track} ${track}.wav
			sleep 2s
			# These two lines add '.wav' to finished of the tracks/song_name variable for rename.
	
			# Change by casper			
			track=`sed -n '1s/$/.wav/p' ${BBBURNDIR}/tracks.txt`
			song_name=`sed -n '1s/$/.wav/p' ${BBBURNDIR}/song_name.txt`			

			# Rename the tracks that has been ripped, by the name 
			# get back by users in prompt.
			mv "${track}" "${song_name}"
			# Remove the song that has been ripped. 
			sed -e '1d' ${BBBURNDIR}/song_name.txt >> ${BBBURNDIR}/temp_song.txt
			mv ${BBBURNDIR}/temp_song.txt ${BBBURNDIR}/song_name.txt
			sed -e '1d' ${BBBURNDIR}/tracks.txt >> ${BBBURNDIR}/temp_tracks.txt
			mv ${BBBURNDIR}/temp_tracks.txt ${BBBURNDIR}/tracks.txt
		fi
	done
	# Remove temp files.
	rm -f ${BBBURNDIR}/tracks.txt
	rm -f ${BBBURNDIR}/song_name.txt
	rm -f ${BBBURNDIR}/*.inf
	 
	eject ${BBCDROM}
	echo -e "${BBSUBCOLOR}$bb_am_rip_2${BBCOLOROFF}"
	sleep 2s
}

# Function Encode Filter Command.
encode_filter()
{
	if [[ "$ENCODEFILTER" != "" ]]; then
		echo -e "${BBTABLECOLOR}|>${BBSUBCOLOR}$bb_am_encfilt(${ENCODEFILTER})${BBCOLOROFF}"			
		`${ENCODEFILTER} ${BBBURNDIR}/*.${format}`
	fi			
}

# CD copying
copy_audio_cd()
{
	# Copy an audio cd.
	cd ${BBBURNDIR}
	# if ${BB_CDAUDIORIP} -D ${BBCDROM} -v all -B -Owav; then
	if ${BB_CDAUDIORIP} -d ${BBCDROM} -B; then    
  		eject ${BBCDROM}
		echo $bb_am_rip_2
		# Normalize WAV's.
		normalization 
		if [[ ${BBNUMDEV} == 1 ]]; then #Check number of devices
			insert_new_CD
		fi
		if eval "${BB_CDBURNCMD} -v dev=${BBCDWRITER} speed=${BBSPEED} $BBOPT_ONE:+\"driveropts=$BBOPT_ONE\" ${BBDTAO} ${BBPADDING} -useinfo ${BBBURNDIR}/*.[Ww][Aa][Vv]"; then
		 	echo $bb_am_ch3_1
			wait_for_enter
		else
			echo $bb_am_ch3_2
			wait_for_enter
		fi
	else
  		echo "$bb_am_ch3_3${BBCDROM}"
		wait_for_enter
	fi
}

# Copy an audio cd to HD
copy_cd_to_hd()
{
	cd ${BBBURNDIR}
	# ${BB_CDAUDIORIP} -D ${BBCDROM} -v all -B -Owav
	${BB_CDAUDIORIP} -d ${BBCDROM} -B
	eject ${BBCDROM}
	  
	# Normalize WAV's.
	normalization
	  
	echo "$bb_am_ch4_1${BBBURNDIR}.$bb_am_ch4_2"
	echo $bb_am_ch4_3
	wait_for_enter                
}

# Create Mp3s from Wavs in BURNDIR (Is this comment _REALLY_ necessary?)
create_mp3s_from_wavs()
{
	cd ${BBBURNDIR}
	BB_TEMPFILE=$(mktemp)

	$(find ./ -iname "*.[Ww][Aa][Vv]" > $BB_TEMPFILE)
  
	cat $BB_TEMPFILE | while read file; do
	    ${BB_MP3ENC} --preset cd "${file}" "${file%%wav}.mp3"
	done

	if [[ "$(cat $BB_TEMPFILE | wc -l)" -gt 0 ]]; then
	  	# Encode Filter Command. 
	  	format=mp3
		encode_filter
	else
	 	echo; echo "$bb_am_ch6_3${BBBURNDIR}"
	fi
	sleep 2s
	rm "$BB_TEMPFILE"
	continue
}

#Create Oggs from Wavs in BURNDIR
create_oggs_from_wavs()
{
	cd ${BBBURNDIR}
	BB_TEMPFILE=$(mktemp)
	  
	$(find ./ -iname "*.[Ww][Aa][Vv]" > $BB_TEMPFILE)

	cat $BB_TEMPFILE | while read file; do
	    ${BB_OGGENC} -b ${BBBITRATE} "${file}"
	done

	if [[ "$(cat $BB_TEMPFILE | wc -l)" -gt 0 ]]; then
	  	# Encode Filter Command. 
	  	format=ogg
		encode_filter
	else
		echo; echo "$bb_am_ch6_3${BBBURNDIR}"
	fi
	sleep 2s
	rm "$BB_TEMPFILE"
	continue
}

# Create flacs from Wavs in BURNDIR
create_flacs_from_wavs()
{
	cd ${BBBURNDIR}
	BB_TEMPFILE=$(mktemp)
 
	$(find ./ -iname "*.[Ww][Aa][Vv]" > $BB_TEMPFILE)
	
	cat $BB_TEMPFILE | while read file; do
	    ${BB_FLACCMD} "${file}"
	done

	if [[ "$(cat $BB_TEMPFILE | wc -l)" -gt 0 ]]; then
	  	# Encode Filter Command. 
	  	format=flac
		encode_filter
	else
		echo; echo "$bb_am_ch6_3${BBBURNDIR}"
	fi
	sleep 2s
	rm "$BB_TEMPFILE"
	continue
}

# Create Mp3s from an audio cd.
create_mp3s_from_cd()
{
	#First, name and rip the tracks
	  
	# Give name to the tracks.
	named
	# Rip the tracks in wav audio file.
	rip
	# Normalize WAV's.
	normalization
	#Now create the Mp3s

	BB_TEMPFILE=$(mktemp)
	$(find ./ -iname "*.[Ww][Aa][Vv]" > $BB_TEMPFILE)

	cat $BB_TEMPFILE | while read file; do
	    ${BB_MP3ENC} --preset cd "${file}" "${file%%.wav}.mp3"
	done

	if [[ "$(cat $BB_TEMPFILE | wc -l)" -gt 0 ]]; then
	  	# Encode Filter Command. 
		format=mp3
		encode_filter
	else
	    echo; echo "$bb_am_ch6_3${BBBURNDIR}"
	    sleep 2s
	    continue
	fi
	
	rm "$BB_TEMPFILE"
	echo "$bb_am_ch9_2${BBBURNDIR}"
	rm ${BBBURNDIR}/*.[Ww][Aa][Vv]
	wait_for_enter
}

# Create Oggs from an audio cd.
create_oggs_from_cd()
{
	#First, name and rip the tracks
	  
	# Give name to the tracks.
	named
	# Rip the tracks in wav audio file.
	rip
	# Normalize WAV's.
	normalization
	
	#Now create the Oggs.

	BB_TEMPFILE=$(mktemp)
	$(find ./ -iname "*.[Ww][Aa][Vv]" > $BB_TEMPFILE)

	cat $BB_TEMPFILE | while read file; do
	    ${BB_OGGENC} -b ${BBBITRATE} "${file}"
	done

	if [[ "$(cat $BB_TEMPFILE | wc -l)" -gt 0 ]]; then
	    # Encode Filter Command. 
	    format=ogg
	    encode_filter
	else
	    echo; echo "$bb_am_ch6_3${BBBURNDIR}"
	    sleep 2s
	    continue
	fi

	rm "$BB_TEMPFILE"
	echo "$bb_am_ch10_2${BBBURNDIR}"
	rm ${BBBURNDIR}/*.[Ww][Aa][Vv]
	wait_for_enter
}

# Create flacs from cd
create_flacs_from_cd()
{
	# Give name to the tracks.
	named
	# Rip the tracks in wav audio file.
	rip
	# Normalize WAV's.
	normalization
	  
	# Now create Flacs

	BB_TEMPFILE=$(mktemp)
	$(find ./ -iname "*.[Ww][Aa][Vv]" > $BB_TEMPFILE)

	cat $BB_TEMPFILE | while read file; do
	    ${BB_FLACCMD} "${file}"
	done

	if [[ "$(cat $BB_TEMPFILE | wc -l)" -gt 0 ]]; then
	    # Encode Filter Command. 
	    format=flac
	    encode_filter
	else
	    echo; echo "$bb_am_ch6_3${BBBURNDIR}"
	    sleep 2s
	    continue
	fi

	rm "$BB_TEMPFILE"
	echo "$bb_am_ch11_1${BBBURNDIR}"
	rm ${BBBURNDIR}/*.[Ww][Aa][Vv]
	wait_for_enter			
}
