#!/bin/sh

base_dir="${HOME}/Music"
hq_dir="highest-quality-links"
music_dir="flac mp3-320kbit mp3-240kbit mp3-160kbit mp3-128kbit"

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

# Flush out the hq directory first of all
rm -Rf ${base_dir}/${hq_dir}/*

artists=0
albums=0

for this_high_dir in ${music_dir}
do
  # Scan for artists
  echo "Scanning ${this_high_dir} directory ..."
  ls -1 "${base_dir}/${this_high_dir}" > ${tmpy}/${this_high_dir}

  while read artist
  do
    # Work out if we already have a directory for this artist
    if [ ! -d "${base_dir}/${hq_dir}/${artist}" ]; then
        mkdir "${base_dir}/${hq_dir}/${artist}"
        artists=`expr $artists + 1`
    fi

    # Scan for tracks
    echo "  Found ${artist} - scanning for albums ..."
    ls -1 "${base_dir}/${this_high_dir}/${artist}" > ${tmpy}/${this_high_dir}-${artist}

    while read album
    do
      # Create a symbolic link to the album
      if [ ! -L "${base_dir}/${hq_dir}/${artist}/${album}" ]; then
        echo "    Linking to ${album}"
	      ln -s "../../${this_high_dir}/${artist}/${album}" "${base_dir}/${hq_dir}/${artist}/${album}"
        albums=`expr $albums + 1`
      fi
    done <${tmpy}/${this_high_dir}-${artist}
  done <${tmpy}/${this_high_dir}
done

echo ""
echo "Found and linked ${artists} artists and ${albums} albums."
