#! /bin/bash
# made by Erik Bergh
# erik.bergh@hiof.no
# msn@gakkgakk.org
#
# Requires Exiftool (http://owl.phy.queensu.ca/~phil/exiftool/)
# 
# Goes trough a folder with unsorted mp3s and uses exiftool to get id3 information
# Then see if there is a folder for Artist and Album in destination. If not making folder(s).
# And moves mp3s to the folder
#
# usage: cleanup


# allowed extentions
extentions=(mp3 MP3)

# browsing music dir

for file in $Source*
  do
  # if not a directory
  if [ ! -d "$file" ] ; then
      ext=${file##*.}
      # checking if a file has a valid extention
      for i in ${extentions[@]}; do
	  if [ "$ext" = "${i}" ]; then
	      # getting artist name
              newfile=`echo $file | tr -t ' ' '_'`
              mv "$file" "$newfile";
              Title=`exiftool -Title $newfile | perl -ne '/: (.*)/; print $1'`
	      Artist=`exiftool -Artist $newfile | perl -ne '/: (.*)/; print $1'`
	      Album=`exiftool -Album $newfile | perl -ne '/: (.*)/; print $1'`
              artist=`echo "$Artist" | tr -t ' ' '_'`
	      album=`echo "$Album" | tr -t ' ' '_'`
              dir="$artist";
	     
              if [ -d "$artist" ]; then
		 if [ -d "$album" ]; then 
		    echo "Moving $newfile til $artist/$album"
		    mv "$newfile" "$artist/$album/"
                 else
                    echo "Making $artis/$album"
		    mkdir "$artist/$album"
                    echo "Moving $newfile til $artist/$album"
		    mv "$newfile" "$artist/$album/"
                 fi
	      else
	        echo "Making $artis/$album"
		mkdir $artist
		mkdir "$artist/$album"
	        echo "Moving $newfile til $artist/$album"
		mv "$newfile" "$artist/$album/"
	     fi
	 fi
      done
  fi
done

