#!/bin/sh
# for file in /media/mp3/Drallibotrop\ -\ Maxi\ --\ Jamendo\ -\ OGG\ Vorbis\ q8\ -\ 2005.10.13\ \[www.jamendo.com\]/*ogg; do echo ${file}; oggdec -o tmp.wav "${file}"; nfile=`echo "${file}" | sed -e "s/.ogg/.mp3/"`; lame -b 160 -cbr tmp.wav "${nfile}";  done

print_usage()
{
    echo "ogg2mp3 decoder - Version 0.1"
    echo ""
    echo "Published under GPL version 2 or later (at your option)"
    echo "Copyright 2007 by Fabian Nowak <timystery@arcor.de>"
    echo ""
    echo "Usage: "
    echo "ogg2mp3 [ OPTION ] | [ input_directory output_directory [ tmp_file ] ]"
    echo "where OPTION is one of the following:"
    echo "  -h, --help    Print this help dialog"
    echo ""
}


if [ "$1" = "-h" -o "$1" = "--help" ]; then
    print_usage
    exit 0
fi

if [ -z "$1" -o -z "$2" ]; then
    echo "Not enough arguments given. Run ogg2mp3 --help for more information."
    exit 1
fi;

indir=$1
outdir=$2
tmpfile=$3

# Use default temporary file if needed 
if [ -z "${tmpfile}" ]; then
    echo "Using /tmp/tmp.wav as temporary wave file."
    tmpfile="/tmp/tmp.wav"
fi

# Check for valid input directory
if [ ! -d "${indir}" ]; then
    echo "The specified input directory is not a valid directory path."
    exit 0
fi

# Check for valid output directory
if [ ! -d "${outdir}" ]; then
    echo "The specified output directory is not a valid directory path."
    exit 0
fi

# Iterate over all OGG files in indir

files=`find "${indir}" -name *.ogg -type f`

OLD_IFS=$IFS
NEWLINE='
'

raw_indir=`echo "${indir}" | sed -e 's/[^[:alnum:]]/\\\&/g'`
raw_outdir=`echo "${outdir}" | sed -e 's/[^[:alnum:]]/\\\&/g'`
IFS=$NEWLINE
for file in ${files}; do
    nfile=`echo "${file}" | sed -e 's/'"${raw_indir}"'/'"${raw_outdir}"'/'`
    nfile=`echo "${nfile}" | sed -e "s/.ogg/.mp3/"`

    oggdec -o "${tmpfile}" "${file}"

    if [ ! -f "${tmpfile}" ]; then
        echo "Could not write to ${tmpfile}. Aborting."
        exit 0
    fi

    lame -b 160 -cbr ${tmpfile} "${nfile}"
    
    if [ -f "${tmpfile}" ]; then
        echo "Deleting temporary wave file..."
        rm ${tmpfile}
    fi
done
IFS=$OLD_IFS

