#!/bin/bash
#
# Convert all flac files to mp3 @ 128k using lame
#
# Thanks to http://blog.tordeu.com/?p=184 for snippets
#

if [ $1 ]; then
  do_artist=$1
else
  do_artist=""
fi

base_dir="${HOME}/Music"
high_dir="flac"

tmpy=/tmp/flac_downto_128k

bits_out=128
out_dir="mp3-${bits_out}kbit-resampled"

# Some stat counters
let n_artists=0
let n_albums=0
let n_tracks=0
let n_artists_r=0
let n_albums_r=0
let n_tracks_r=0
let n_artists_c=0
let n_albums_c=0
let n_tracks_c=0
last_artist=""
last_album=""

# Create a tmp directory for dumps
if [ ! -d "${tmpy}" ]; then
  mkdir ${tmpy}
fi

# Scan through all of the high quality directories
for this_high_dir in ${high_dir}
do
  # Scan for artists
  echo "Scanning ${this_high_dir} directory ..."
  ls -1 "${base_dir}/${this_high_dir}" > ${tmpy}/${this_high_dir}

  # Scan for albums
  while read artist
  do
    if [ "${do_artist}" = "" ] || [ "${do_artist}" = "${artist}" ]; then
      let n_artists=$n_artists+1
      # Scan for tracks
      echo "  Found ${artist} - scanning for albums ..."
      artist_clean=`echo ${artist//[ \[\]()&\'\"\,\’:*?]/_} | tr -s _ _ `
      if [ "${artist}" != "${artist_clean}" ]; then
        echo "  Renaming ${artist} to ${artist_clean}"
        mv "${base_dir}/${this_high_dir}/${artist}" "${base_dir}/${this_high_dir}/${artist_clean}"
        artist=${artist_clean}
        let n_artists_r=$n_artists_r+1
      fi
      ls -1 "${base_dir}/${this_high_dir}/${artist}" > ${tmpy}/${this_high_dir}-${artist}

      while read album
      do
        let n_albums=$n_albums+1
        echo "    Found ${album} - scanning for tracks ..."
        album_clean=`echo ${album//[ \[\]()&\'\"\,\’:*?]/_} | tr -s _ _ `
        if [ "${album}" != "${album_clean}" ]; then
          echo "    Renaming ${album} to ${album_clean}"
          mv "${base_dir}/${this_high_dir}/${artist}/${album}" "${base_dir}/${this_high_dir}/${artist}/${album_clean}"
          album=${album_clean}
          let n_albums_r=$n_albums_r+1
        fi

        ls -1 "${base_dir}/${this_high_dir}/${artist}/${album}" > ${tmpy}/${this_high_dir}-${artist}-${album}

        # Now the fun bit ... let's start re-encoding the track we've just found
        while read track
        do
          track_clean=`echo ${track//[ \[\]()&\'\"\,\’:*?]/_} | tr -s _ _ `
          if [ "${track}" != "${track_clean}" ]; then
            echo "      Renaming ${track} to ${track_clean}"
            mv "${base_dir}/${this_high_dir}/${artist}/${album}/${track}" "${base_dir}/${this_high_dir}/${artist}/${album}/${track_clean}"
            track=${track_clean}
            let n_tracks_r=$n_tracks_r+1
          fi

	  this_source="${base_dir}/${this_high_dir}/${artist}/${album}/${track}"
	  this_dest=`echo ${base_dir}/${out_dir}/${artist}/${album}/${track} | sed 's/.flac/.mp3/g'`

  	  # Check that it's a FLAC file
	  if [ `file "${this_source}" | grep -c "FLAC audio bitstream data"` = "1" ]; then
            let n_tracks=$n_tracks+1

            # Check the datestamps
	    source_date=`stat -c %Y "${this_source}"`
	    if [ -f "${this_dest}" ]; then
	      dest_date=`stat -c %Y "${this_dest}"`
	    else
	      dest_date=0
	    fi

   	    #  Only encode or copy if dest is older than source
	    if [ ${dest_date} -lt ${source_date} ]; then
	      ##############################################
	      # Time to do what we were sent here to do!!! #
	      ##############################################

              # Get tag data from source. 
	      # Artist
	      s_artist=`metaflac --show-tag=ARTIST "${this_source}" | awk -F "=" '{print $2}'`
	      # Album
	      s_album=`metaflac --show-tag=ALBUM "${this_source}" | awk -F "=" '{print $2}'`
	      # Track title
	      s_track=`metaflac --show-tag=TITLE "${this_source}" | awk -F "=" '{print $2}'`
	      # Genre
	      s_genre=`metaflac --show-tag=GENRE "${this_source}" | awk -F "=" '{print $2}'`
	      # Year
	      s_year=`metaflac --show-tag=DATE "${this_source}" | awk -F "=" '{print $2}' | awk -F "-" '{print $1}'`
	      # Track number
	      s_track_no=`metaflac --show-tag=TRACKNUMBER "${this_source}" | awk -F "=" '{print $2}'`
	      if [ `expr length "$s_track_no"` -eq 1 ]; then
	        s_track_no="0${s_track_no}"
	      fi

	      d_args="--ta \"${s_artist}\" --tg \"${s_genre}\" --tl \"${s_album}\""
	      d_args="${d_args} --tn \"${s_track_no}\" --tt \"${s_track}\""
              if [ ! ${s_year} = "" ]; then
                d_args="${d_args} --ty \"${s_year}\""
              fi

              # Create the directory if it doesn't exist
	      if [ ! -d "${base_dir}/${out_dir}/${artist}/${album}" ]; then
	        mkdir -p "${base_dir}/${out_dir}/${artist}/${album}"
	      fi
      
	      # Now re-encode
  	      echo "      Re-encoding ${track} (to mp3-${bits_out}kbit)"
	      #echo "flac -c -d \"${this_source}\" 2>/dev/null | lame -B 128 -V 4 ${d_args} - \"${this_dest}\" 2>/dev/null"
	      eval "flac -c -d \"${this_source}\" 2>/dev/null | lame -B 128 -V 4 ${d_args} - \"${this_dest}\" 2>/dev/null"

              let n_tracks_c=$n_tracks_c+1
              if [ "${artist}" != "${last_artist}" ]; then
                let n_artists_c=$n_artists_c+1
              fi
              if [ "${album}" != "${last_album}" ]; then
                let n_albums_c=$n_albums_c+1
              fi
              last_artist=${artist}
	      last_album=${album}

	      ##########################
	      # Wasn't that simple?!?! #
	      ##########################
	    else
	      echo "      Skipping ${track} (file up-to-date)"
            fi
	  else
	    # Not a flac, so just copy (if not already up-to-date)
            # Check the datestamps
	    source_date=`stat -c %Y "${this_source}"`
	    if [ -f "${this_dest}" ]; then
              dest_date=`stat -c %Y "${this_dest}"`
	    else
  	      dest_date=0
	    fi
	    # Copy or skip?
	    if [ ${dest_date} -lt ${source_date} ]; then
              # Create the directory if it doesn't exist
	      if [ ! -d "${base_dir}/${out_dir}/${artist}/${album}" ]; then
	        mkdir -p "${base_dir}/${out_dir}/${artist}/${album}"
	      fi

	      echo "      Copying  ${track} as not a flac"
	      cp "${this_source}" "${this_dest}"
	    else
	      echo "      Skipping ${track} (file up-to-date)"
            fi
	  fi
        done <${tmpy}/${this_high_dir}-${artist}-${album}
      done <${tmpy}/${this_high_dir}-${artist}
    fi
  done <${tmpy}/${this_high_dir}
done
  
echo ""
echo "Found ${n_tracks} tracks in ${n_albums} albums from ${n_artists} artists"
echo "Renamed ${n_tracks_r} tracks, ${n_albums_r} albums and ${n_artists_r} artists"
echo "Converted ${n_tracks_c} tracks in ${n_albums_c} albums from ${n_artists_c} artists"
echo ""

# Now clean up the tmp area
""rm -f -R ${tmpy}
