#!/bin/bash

# ogg2ogg: converts OGG music to smaller (lower quality) OGG files, 
#   preserving ID3 tags
# Author:  Martin Meyerspeer
# Feel free to use, but absolutely without warranty.
# 
# requires:  ogginfo, oggdec and oggenc  (besides bash, ...)
#
# command line parsing and come functions from: 
# http://gimpel.gi.funpic.de/wiki/index.php?title=Howto:convert_aac/mp4_to_wav/mp3/ogg_on_Linux
# which is in turn based on a script example from:
# http://gimpel.gi.funpic.de/Howtos/convert_aac/index.html

OGG2OGG=`basename ${0}`
QUALITY=3
WAVDIR="/tmp"
INFOFILE="/tmp/infofile"

do_usage() {            # explanatory text
  echo "usage: ${OGG2OGG} [-q n] [file list]|[input dir [output dir]]"
  echo "  Convert OGG music to smaller (lower quality) OGG files, preserving ID3 tags"
  echo "  New file name:  file_q[quality].ogg"
  echo "  -q n    Quality (default: 3)"
  echo "  -r      recursive (convert directory of OGG files)"
  echo "  -h      This information"
  exit 0
  }

do_error() {
echo "$*"
exit 1
}

do_convert_file() {
# ogginfo $INFILE

ogginfo "${1}" > ${INFOFILE}

NOMBITRATE=$(grep '^Nominal bitrate: ' ${INFOFILE} | awk '{print ($3)}')
TITLE=$(grep 'title=' ${INFOFILE} | cut -d'=' -f 2)
ARTIST=$(grep 'artist=' ${INFOFILE} | cut -d'=' -f 2)
GENRE=$(grep 'genre=' ${INFOFILE} | cut -d'=' -f 2)
DATE=$(grep 'date=' ${INFOFILE} | cut -d'=' -f 2)
ALBUM=$(grep 'album=' ${INFOFILE} | cut -d'=' -f 2)
TRACKNUM=$(grep 'tracknumber=' ${INFOFILE} | cut -d'=' -f 2)

rm ${INFOFILE}

oggdec -o "${2}" "${1}"
oggenc -q $QUALITY -a "$ARTIST" -d "$DATE" -G "$GENRE" -N "$TRACKNUM" -l "$ALBUM" -t "$TITLE" -o "${3}" "${2}"
rm "${2}"
##              -b $NOMBITRATE \
}

do_convert_dir() {
####  cd "${1}"
  for INFILE in "${1}"/*.ogg
  do
    if [ "${INFILE}" == "${1}"/"*.ogg" ]
      then
      do_error "No files with extension .ogg in this directory."
   fi

    echo "$INFILE"
    INFILEBASENAME=`basename "${INFILE}"`
    WAVFILE="$WAVDIR"/"${INFILEBASENAME%.ogg}".wav
    OUTFILE="${2}"/"${INFILEBASENAME}"
    
    do_convert_file "${INFILE}" "${WAVFILE}" "${OUTFILE}"
    
  done	

}



GETOPT=`getopt -o q:rh -n ${OGG2OGG} -- "$@"`
if [ $? -ne 0 ]
then
  do_usage
fi

eval set -- "$GETOPT"

while true
do
  case "${1}" in
  -q) QUALITY=$2 ; shift ; shift ;;
  -r) RECURSIVE="yes" ; shift ;;
  -h) do_usage ;;
  --) shift ; break ;;
  *)  do_usage ;;
  esac
done


if [ $# -eq 0 ]
then                    # Convert all files in current directory
  for INFILE in *.ogg
  do
    if [ "${INFILE}" == "*.ogg" ]
      then
      if [ "${RECURSIVE}" == "yes" ]
      then 
        do_error "No input directroy given."
      fi
      do_error "No files with extension .ogg in this directory."
   fi

    echo $INFILE
    WAVFILE="${WAVDIR}"/"${INFILE%.ogg}".wav
    OUTFILE="${INFILE%%.ogg}"_q${QUALITY}.ogg
    
    do_convert_file "${INFILE}" "${WAVFILE}" "${OUTFILE}"
    
  done	
else                    # Convert listed files or a directy
if [ "${RECURSIVE}" == "yes" ]               # for dierectory
  then
  INDIR=`echo "${1}" | sed 's/\/$//'`        # remove trailing slash
  test -d "${INDIR}" || do_error "${INDIR} not a directory."
  if [ $# == 1 ]
  then
    OUTDIR="${INDIR}"_q${QUALITY}
  else 
    if [ $# == 2 ]
    then 
    OUTDIR=`echo "${2}" | sed 's/\/$//'`     # remove trailing slash
    else
      do_error "Only 1 or 2 arguments allowed in recursive mode."
    fi
  fi
  test -e "${OUTDIR}" && do_error "${OUTDIR} exists.  Remove before use."
  echo  creating "$OUTDIR"
  mkdir "$OUTDIR"
  do_convert_dir "${INDIR}" "${OUTDIR}"
else                   # for listed files
  for INFILE in ${*}   # this line causes trouble for files names with spaces
    do
      test -f "${INFILE}" || do_error "${INFILE} not an OGG file."
      WAVFILE="${WAVDIR}"/"${INFILE%.ogg}".wav
      OUTFILE="${INFILE%%.ogg}"_q${QUALITY}.ogg
    
      do_convert_file "${INFILE}" "${WAVFILE}" "${OUTFILE}"
      
    done 
  fi
fi

exit 0

