#!/bin/bash

if [ $# -ne 2 ]; then
	echo "Usage:"
	echo "$0 <input mp3 filename> <output Vorbis filename>"
	echo
	echo "`basename $0` relies on mktemp, Vorbize, and mpg123 being able to decode your mp3."
	exit 1
fi

base=`basename $0`
TEMPFILE=`mktemp -q /tmp/$base.XXXXXX`
if [ $? -ne 0 ]; then
	echo "Unable to create temporary file."
	exit 1
fi

VORBIZE=`which vorbize`
if [ $? -ne 0 ]; then
	if [ -f ./vorbize ]; then
		VORBIZE=./vorbize
	else
		echo "Unable to find Vorbize. Try 'make install' in the Vorbize directory."
	fi
fi

echo "Vorbis streams have three fields: Artist, Album, and Track:"
read -p "Enter artist: " ARTIST
read -p "Enter album:  " ALBUM
read -p "Enter track:  " TRACK

echo "ok."

echo "Decoding mp3 using mpg123..."
mpg123 -w "$TEMPFILE" -v "$1"

if [ $? -ne 0 ]; then
	echo "Error running mpg123."
	exit 1;
fi

echo "Encoding Ogg Vorbis stream using Vorbize..."
$VORBIZE -w "$2" --artist "$ARTIST" --album "$ALBUM" --track "$TRACK" "$TEMPFILE"

if [ $? -ne 0 ]; then
	echo "Error running Vorbize. Leaving temporary file $TEMPFILE."
	exit 1;
fi

rm -f $TEMPFILE

echo "Conversion complete."
