#! /bin/bash
# Example script for use with worker
# converts CD tracks to other formats
# based on scripts by Giulio Canevari <giuliogiuseppecarlo@interfree.it>

if [ "$#" -lt "1" ]; then
  echo "$0 <title1> ..."
  exit 5
fi

case "`basename $0`" in
  cd2flac*)
    MODE="flac"
    PROGS="cdparanoia normalize flac"
    ;;
  cd2mp3*)
    MODE="mp3"
    PROGS="cdparanoia normalize lame"
    ;;
  cd2ogg*)
    MODE="ogg"
    PROGS="cdparanoia normalize oggenc"
    ;;
  *)
    MODE="wav"
    PROGS="cdparanoia normalize"
    ;;
esac

for i in $PROGS; do
  if [ -z "`which $i 2>/dev/null`" ]; then
    echo "You need $i to run this script!"
    exit 5
  fi
done

if [ -z "$TMP" ]; then
  TMP=/tmp
fi

for T in $*; do
  while true; do
    TF="$TMP/worker-$$-$RANDOM.wav"
    if [ ! -e "$TF" ]; then
      touch "$TF"
      chmod 0600 "$TF"
      break
    fi
  done
  cdparanoia $T "$TF"
  normalize "$TF"
  case "$MODE" in
    flac)
      flac --best "$TF" -o Track-$T.flac
      ;;
    mp3)
      lame -b 256 "$TF" Track-$T.mp3
      ;;
    ogg)
      oggenc -q 8 "$TF" -o Track-$T.ogg
      ;;
    *)
      mv "$TF" Track-$T.wav
      ;;
  esac
  rm -f "$TF"
done
