#!/bin/bash

# Naudilus - Nautilus script for audio file conversion
# by Rafael Rigues <<EMAIL: PROTECTED>> - 02/28/2002
# Translations and feedback are welcome!

# Depends on lame (3.91 recommended), gidalog and vorbis tools and libraries (rc 3 or newer)
# Based on code from convert_to_jpeg (David Westlund)
# Based on code from Archiver/Unarchiver (Patrick Largey & David Westlund)
# Thanks to Aurlio Marinho Jargas for miscellaneous help

# Put on ~/.gnome/nautilus-scripts, and chmod +x it!

# Changelog:

# 03/17/2002	* Version 0.5
#		* Info: This version was finished on 03/05/2002, and was meant for personal use only.
#		  (at least until I had implemented everything I wanted). However, I'm releasing it now
#		  to get feedback from other users.
#		* I've discovered the cause for oggenc always encoding files at 342 kbps. It seems to
#		  be a bug triggered by the combination of glibc-2.2.4-19.3 and vorbis rc 1. Upgrading
#		  the vorbis tools and libraries to rc 3 solved the problem.
#		* I've also found that not all versions of lame have the --decode option. I don't know
#		  when it was added to lame (and I'm too lazy to check the changelog now), but I'm
#		  using lame 3.91.
#		* Now I'm using pipes to decode/encode the file simultaneously (thanks to FRS for being
#		  so persistent about this), so there's no need to create (and delete, afterwards) a
#		  temporary WAV file. It's also one less thing to check if it will be overwritten or not.
#		* More code cleanups. "...Smarter! Stronger! More Aggressive! I feellike I could..." :)
#		* Now also converts WAVE files to MP3 or Vorbis!

# 03/03/2002	* Version 0.4

#		* Spent a whole day trying to reorganize the code, tighten it up and make it look
#		  smarter and prettier. Did I succeed? :)
#		* Now Naudilus detects if the file exists (both the temporary .wav file created during
#		  the conversion and the resulting .mp3 or .ogg file) and asks the user if he wants the
#		  the file to be overwritten. If not, the file is ignored, and Naudilus will proceed
#		  with the next file.
#		* I've found a strange bug where oggenc is now ALWAYS encoding the files at an average
#		  342 Kbps, regardless of the arguments I pass to it. I suspect it is a fault on the ogg
#		  encoder, caused by a full-scale system update (which included a new version of glibc) I
#		  did today. I will find out more about this tomorrow, when I test the script on my
#		  machine at work.

# 03/02/2002	* Version 0.3

#		* Naudilus now asks which format to convert the files to. Note that if you choose
#		  to convert a file to it's current format (eg. convert an MP3 file to MP3), it
#		  will be simply ignored, and Naudilus will proceed with the next file.
#		* Possible conversions are: MP3 -> WAV, Ogg -> WAV, MP3 -> Ogg and Ogg -> MP3.

# 03/01/2002	* Version 0.2

#		* Changed the name to "Naudilus". Thanks to Fabio Ricardo Schmidlin for the name!
#		* Detects the filetype before attempting to convert the file.
#		* Uses the file extension to determine which kind of file it is, if the filetype
#		  detection fails.
#		* Added Vorbis to MP3 conversion.

# 02/28/2002	* First version. It seems to work! :) 

# And now, the incredible, ever expanding TO-DO list!!

# 	* Check for write permission before trying to create a file. If such permission does not exist, ask
#	  the user where to write the file.
#	* Recurse directories and subdirectories (Dangerous??)
#	* Generate MP3/Ogg files with complete tags (artist, album, genre, etc...). Grab the tags from the 
#	  original MP3/Ogg file 

# Talk is cheap! Now show me the code!!!

# Version number

version="0.5"

# Messages
		# English, by Myself
		wait="Naudilus "$version" - Please Wait..."
		warning="Naudilus "$version" - WARNING!"
		converting="Converting your audio files. Get some coffee and come back later"
		which_format="Convert files to which format?"
		format_mp3="Mpeg Layer III (MP3)"
		format_ogg="Ogg Vorbis"
		format_wav="Microsoft WAV"
		overwrite="The file: "
		proceed=" will be overwritten. Proceed?"

case $LANG in

	pt* )
		# Brazilian Portuguese, also by Myself	
		wait="Naudilus "$version" - Aguarde..."
		warning="Naudilus "$version" - AVISO!"
		converting="Convertendo seus arquivos de udio. Pegue um caf e volte mais tarde"
		which_format="Converter arquivos para qual formato?"
		format_mp3="Mpeg Layer III (MP3)"
		format_ogg="Ogg Vorbis"
		format_wav="Microsoft WAV"
		overwrite="O arquivo: "
		proceed=" ser sobrescrito. Devo continuar?";;


	fr* )
		wait=3D"Naudilus "$version" - Veuillez patienter..."
                warning=3D"Naudilus "$version" - ATTENTION!"
                converting=3D"La conversion de vos fichiers audio est en cours, veuillez prendre un caf=E9 et revenir plus tard"
                which_format=3D"Dans quel format voulez-vous convertir le(s) fichier(s)?"
                format_mp3=3D"Mpeg Layer III (MP3)"
                format_ogg=3D"Ogg Vorbis"
                format_wav=3D"Microsoft WAV"
                overwrite=3D"Le fichier : "
                proceed=3D" sera =E9cras=E9, voulez-vous poursuivre?";;

	eo* )
		wait="Naudilus "$version" - Bonvolu atendi..."
		warning="Naudilus "$version" - AVERTU!"
		converting="Konvertas viajn aŭdiajn dosierojn.  Trinku iom da kafo kaj revenu poste."
		which_format="Konvertu dosierojn al kiu formato?"
		format_mp3="Mpeg Layer III (MP3)"
		format_ogg="Ogg Vorbis"
		format_wav="Microsoft WAV"
		overwrite="La dosiero: "
		proceed=" estas superskribota.  ?u procedu?";;

	sv*)
		wait="Naudilus "$version" - Var god vnta..."
		warning="Naudilus "$version" - Varning!"
		converting="Konverterar dina ljudfiler. Hmta lite kaffe och kom tillbaks senare"
		which_format="Vilket format ska filerna konverteras till?"
		format_mp3="Mpeg Lager III (MP3)"
		format_ogg="Ogg Vorbis"
		format_wav="Microsoft WAV"
		overwrite="Filen: "
		proceed=" Kommer skrivas ver. Vill du fortstta?";;

esac

# Select file format to convert file to

selected_format=`gdialog --title "Naudilus "$version"" --radiolist "$which_format" 260 100 3 ".ogg" "$format_ogg" on ".mp3" "$format_mp3" off ".wav" "$format_wav" off 2>&1`

if [ "$selected_format" != "" ]
then
	# Do Nothing...
	echo "$selected_format" > /dev/null
else
	exit 0
fi

# Warn the user that the conversion will take a LONG time...

gdialog --title "$wait" --msgbox "$converting" 100 100&

# Do the conversion

while [ $# -gt 0 ]; do

	in_file=$1
	out_file=`echo "$in_file" | sed 's/\.\w*$/'$selected_format'/'`

	while `true`; do

		# Is the input file different from the output file?
		
		if  [ "$in_file" = "$out_file" ]
		then
			# No, break and go to the next file...
			break
		fi

		# Does the output file exists? If yes, asks the user if he wants to
		# overwrite.

		if [ "`ls "$out_file" | grep -v "^ls"`" != "" ]
		then
			if !(`gdialog --title "$warning" --yesno "$overwrite \"$out_file\"$proceed" 200 100`)
			then
				# Don't owerwrite, so we get out of here.
				break
			fi
		fi

		# Lets see... Is it an MP3 file?
		# Some MP3 files created with Apple's iTunes or some Windows encoders
		# do not report the correct filetype when the 'file' command is used
		# (it says "data", instead of "MP3, xxx kBits, xx.x kHz, Stereo...").
		# So, we need to also check the file extension, and hope it's a real
		# MP3 file...

		if [ "`file -b "$1" | grep 'MP3'`" != "" ] || [ "`echo $in_file | grep -i '\.mp3$'`" != "" ]
		then
			if [ "$selected_format" = ".ogg" ]
			then
				lame --quiet --decode "$in_file" - | oggenc - -Q -b 128 -M 160 -o "$out_file"
			else
				lame --quiet --decode "$in_file" "$out_file"
			fi
			break
		fi

		# Hmmm... Does not have an MP3 signature, nor .mp3 extension. Maybe
		# an Ogg-Vorbis file? Just to be sure, we also check the file extension

		if [ "`file -b "$1" | grep 'Vorbis'`" != "" ] || [ "`echo $in_file | grep -i '\.ogg$'`" != "" ]
		then
			if [ "$selected_format" = ".mp3" ]
			then
				ogg123 -q --device=wav "$in_file" -f - | lame --quiet -m auto -v -F -b 128 -B 160 -h - "$out_file"
			else
				ogg123 -q --device=wav "$in_file" -f "$out_file"
			fi
			break
		fi
		
		# The last resort is to see if it is a .WAV file.. Also checking
		# the file extension, of course!
		
		if [ "`file -b "$1" | grep 'WAVE'`" != "" ] || [ "`echo $in_file | grep -i '\.wav$'`" != "" ]
		then
			if [ "$selected_format" = ".mp3" ]
			then
				lame --quiet -m auto -h -v -F -b 128 -B 160 "$in_file" "$out_file"
			else
				oggenc "$in_file" -Q -b 128 -M 160 -o "$out_file"
			fi
			break
		fi		
		
	break
	shift
	done

shift
done	

# Kill the warning

kill `ps -ef | grep "gdialog --title" | gawk '{ print $8, $2}' | grep gdialog | gawk '{ print $2 }'` 2> /dev/null

