#!/bin/bash
# kaneda@bohater.net
# wma 2 mp3 converter
#
# Main idea from mtron script borrowed...

#bitrate converting with lame
BITRATE=256

if [ -z "$2" ] ; then
  echo "wma2mp3 by kaneda@bohater.net"
  echo "Usage: $0 <dir_with_wma_files> <output_dir>"
  echo "Example: $0 ./soad-live ./soad-live_mp3"
  exit
fi

if [ -d "$2" ] ; then
  echo "Output directory : $2  exist - delete it"
  echo "exiting..."
  exit
fi

#remove uppercase
echo "[+] Removing uppercase from filenames..."
cd "$1"
for i in *.[Ww][Mm][Aa]; do mv "$i" `echo $i | tr '[A-Z]' '[a-z]'` 2>/dev/null ; done

#remove spaces
echo "[+] Removing spaces from filenames..."
for i in *.wma; do mv "$i" `echo $i | tr ' ' '_'` 2>/dev/null ; done

cd ..
echo "[+] Copying files..."

mkdir "$2"
cp $1/*.wma "$2"
cd "$2"

# How many files to make the progress bar
PROGRESS=0
NUMBER_OF_FILES=`find -iname "*.wma"|wc -l`
let "INCREMENT=100/$NUMBER_OF_FILES"

#Rip with Mplayer / encode with LAME
for i in *.wma ; do 
echo "[%] $PROGRESS % Complete...";
echo "[*] Converting file:  $i - with bitrate: $BITRATE [ Patience is a virtue :] ...";
mplayer -vo null -vc dummy -af resample=44100 -ao pcm -waveheader $i 2>/dev/null 1>/dev/null && lame -m s -b $BITRATE audiodump.wav -o $i 1>/dev/null 2>/dev/null; 
let "PROGRESS+=$INCREMENT"
done

#convert file names
for i in *.wma; do mv "$i" "`basename "$i" .wma`.mp3"; 
done

rm audiodump.wav

echo "Process complete..."
echo "You can find Your .mp3 in $2 directory..."
echo "Thank You [ http://kaneda.bohater.net ]"

